Wednesday, October 12, 2016

Synchronization Primitives

Critical section, Mutex, Event, Semaphore and Waitable timers are the different available synchronization objects on windows.

Critical Section

Synchronizes threads (/allows one at a time) to have an access to a shared resource with in a process that it is created in and hence cannot be accessed across processes - limited scope. The remaining primitives have got system wide scope and so can be accessed across processes too.

Mutex

As the name indicates, mutually exclusive, so if one thread gets an access, all others will be on wait (or restrained from accessing) until the first one relinquishes - allows one thread at a time as if the critical sections does but it can be accessed across processes or network boundaries.
e.g. Toll gate (one vehicle per ticket)

Event

Mutex, upon relinquishing, causes to release one thread from the wait to have its turn among all bunch of threads, whereas event releases all the waiting threads in one go. Event signals (/notifies) all the waiting threads when a current thread is done its job.
e.g. Traffic Signals.

Semaphore

It maintains a count between zero and some maximum number, which indicates how many threads can access the shared resource simultaneously. It means one can restrict the no. of accesses to a resource. The count is reduced every time a thread gets an access to semaphore and is incremented every time a thread releases the semaphore. When the count reaches ZERO, no more threads can access the resource. The semaphore state is set to signaled when the count is greater than ZERO and non signaled when it is ZERO.
e.g. Movie tickets

Waitable Timers

Notifies one or more waiting threads that a specified time has arrived. A waitable timer object is a synchronization object whose state is set to signaled when the specified due time arrives. There are two types of waitable timers that can be created: manual-reset and synchronization. A timer of either type can also be a periodic timer.