Thread Synchronization including Mutual Exclusion Mutual exclusive use of shared resources (among multiple threads) Only one can access a shared resource. When a thread acquires a shared resource, another one that wants to access the same resource has to wait until the first thread finishes. Region of code that accesses the shared resource be single threaded (called critical section (CS)) In C++/CLI Mutex 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. 1. A semaphore may be initialized to a nonnegative integer value. 2. The semWait operation decrements the semaphore value. If the value becomes negative, then the process executing the semWait is blocked. Otherwise, the process continues execution. 3. The semSignal operation increments the semaphore value. If the resulting value is less than or equal to zero, then a process blocked by a semWait operation, if any, is unblocked.
Semaphores (2) Semaphore S = 3; P(S) { wait until S>0; S=S-1; } V(S) { S=S+1; }
Semaphores for Mutual Exclusion Shared Data Thread 1 P(S) Access Shared Data V(S) Thread 2 P(S) Access Shared Data V(S)
Semaphores for Synchronization Thread 1 P(S) Print “AAAAA” Thread 2 Print “BBBBB” V(S)
Semaphores in C++/CLI Semaphore ^S = gcnew Semaphore(init, max); S->WaitOne(); S->Release(); or S->Release (count);
Examples