CPP Multi-threading Notes
Synchronization
- Precedence Relationships
- Mutual Exclusive relationships.
Mutex (Mutual Exclusion)
Alpha precedes Beta OR Beta precedes Alpha. (they cannot overlap execution)
semaphore lock = 1; foo(int account, int amount) { wait(lock); t = balance[account]; valance[account] = t - amount; signal(lock); }
Semaphore
Beta precedes Alpha.
Resources managed by semaphore:Characters in FIFO, Spaces in FIFO. (works only with single producer)
Shared Memory
char buf[N];int in = 0, out = 0;semaphore chars = 0;semaphore mutex= 1; // allow one piece pf code, creates a "critical section" between
Only need shared Mutext
if manipulating the ins and outs of the buffer(shared resource).
Producer
send (char c){ wait(space); wait(mutex); buf[in] = c; in = (in + 1) % N; signal(chars); signal(mutex);}
Consumer
char rcv(){ char c; wait(chars); wait(mutex); c = buff[out]; out = (out + 1) % N; signal(mutex); signal(space); return c;}