Tuesday 3 June 2014

Threading Technology C++

1: Lock-related
1) mutex : lock() and unlock()
2) timed_mutex: try_lock_for (time) prevents deadlock;

Example:
#include <mutex>          // std::mutex

std::mutex mtx;           // mutex for critical section

void print_block (int n, char c) {
  // critical section (exclusive access to std::cout signaled by locking mtx):
  mtx.lock();
  for (int i=0; i<n; ++i) { std::cout << c; }
  mtx.unlock();
}

2:Semaphore
1) binary semaphore: it is the same with mutex
2) integer semaphore: it is designed by Dijkstra, to solve Producer & Consumer Problem. Two operations: P (--) and V(++); The limitation is that the integer can not be negative.

Example:

produce:
    P(emptyCount)
    mutex.lock(useQueue)
    putItemIntoQueue(item)
    mutex.unlock(useQueue)
    V(fullCount)

consume:
    P(fullCount)
    mutex.lock(useQueue)
    item ← getItemFromQueue()
    mutex.unlock(useQueue)
    V(emptyCount) 
 
Note: emptyCount is a resource count for P and fullCount is a resource for C.
Semaphore is designed for Logic Control.

3:Monitors
1)rely on High-level languages, like: Java, C#
2) Encapsulate procedures and functions which can only be accessed by 1 thread at once.

Example:
monitor class account {
private:
int balance = 0;
public:
void deposit(int amount) {
balance = balance + amount;
}
void withdraw(int amount) {
balance = balance - amount;
}
};

4: Distributed System Synchronization 
1) LockManager in Master Processor
2) Token-based System
3) Time-based Synchronization (Clock or Logic Clock)



No comments:

Post a Comment