Saturday, July 23, 2011

All about Semaphores

A semaphore is a synchronization mechanism that can be used to manage synchronization relationships and implement the access policies. A semaphore is a special kind of variable that can only be accessed by very specific operations. The semaphore is used to help threads and processes synchronize access to shared modifiable memory or manage access to a device or other resource. The semaphore is used as a key to access the resource. This key can only be owned by one process or thread at a time. Whichever task owns the key or semaphore locks the resource for its exclusive use.

Counting semaphores are used when you might have multiple devices (like 3 printers or multiple memory buffers).

Binary semaphores are used to gain exclusive access to a single resource (like the serial port, a non-reentrant library routine, or a hard disk drive). A counting semaphore that has a maximum value of 1 is equivalent to a binary semaphore (because the semaphore's value can only be 0 or 1.

Mutex semaphores are optimized for use in controlling mutually exclusive access to a resource. There are several implementations of this type of semaphore.

Semaphores can be implemented with a queue and an integer counter. You maintain the set of consumers in the queue, and when a consumer releases the semaphore, you retrieve the next entry in the queue and "wake" them to allow them to enter the critical section. When a consumer requests the semaphore, you simply push them onto the queue. If no one is in the critical section, you go ahead and grant the requester the right to enter the critical section.