Thread Synchronization including Mutual Exclusion in C++/CLI • Mutex – Mutual exclusive use of shared resources (among multiple threads) • When a thread acquired a mutex, the second one that wants to acquire that mutex is suspended until the first thread releases the mutex – Region of code that accesses the shared resource be single threaded (called critical section) – Acquire and release by the same thread. • Monitor – Mutual exclusive on the specified object • Semaphore Semaphores (1) • Semaphore: – Allow a maximum number of concurrent accesses to the shared resources – Does not enforce thread identity – An integer value used for signalling among processes. • A signal that many threads/processes read/update to cooperate in order to enter a critical section. – To enter a CS: check semaphore, either blocked, or go ahead ( need to set the signal to block others) – To leave a CS, unset the signal to unblock others. Semaphores (2) • Three operations on a semaphore, all atomic: – Initialize (to nonnegative) – Decrement (P() operation) • When each time a thread enters the semaphore • If the value is zero, the subsequent P() requests block until other threads release the semaphore • Otherwise, the process continues execution – increment (V() operation) • When a thread releases the semaphore • When all threads have released the semaphore, the count is at the maximum value specified when the semaphore was created. Semaphores (3) • Semaphore S = 3; • P(S) { wait until S>0; S=S-1; } • V(S) { S=S+1; } Semaphores for Mutual Exclusion Semaphore S = 1; Shared Data Thread 1 • P(S) Thread 2 • P(S) • Access Shared Data • Access Shared Data • V(S) • V(S) Semaphores for Synchronization Semaphore S = 0; Thread 1 Thread 2 • P(S) • Print “AAAAA” • Print “BBBBB” • V(S) Semaphores in C++/CLI • Semaphore ^S = gcnew Semaphore(init, max); • S->WaitOne(); • S->Release(); or S->Release (count); Examples