Thread Synchronization including Mutual Exclusion Mutual exclusive use

  • Slides: 7
Download presentation
Thread Synchronization including Mutual Exclusion Mutual exclusive use of shared resources (among multiple threads)

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

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) • Semaphore S = 3; • P(S) { wait until S>0; S=S-1;

Semaphores (2) • 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)

Semaphores for Mutual Exclusion Semaphore S = 1; Shared Data Thread 1 • P(S) Thread 2 • P(S) • Access Shared Data • V(S)

Semaphores for Synchronization Semaphore S = 0; Thread 1 Thread 2 • P(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->Wait. One(); •

Semaphores in C++/CLI • Semaphore ^S = gcnew Semaphore(init, max); • S->Wait. One(); • S->Release(); or S->Release (count);

Examples

Examples