Search

Introduction to semaphores using animation

Semaphores can be defined as a tool to protect the access to a common resource while it is being accessed by multiple tasks or processes at the same time.

If the semaphore is used to allow access to the shared resource by only one process, then the semaphore is termed as a mutex or binary semaphore.

If the semaphore is used to allow access to the shared resource by more than one process, then the semaphore is termed as counting semaphore and the number of processes allowed to access the shared resource will depend on the initialization of the semaphore.

The basic functionality of semaphore is based on two operations or functions "signal" and "wait". Any process which needs access to a shared resource protected by a semaphore needs to call the function "wait" on the semaphore. If the semaphore is free then the process will be allowed to lock the semaphore and proceed to access the shared resource. On the other hand if the semaphore is already locked by another process then the new process will have to wait until the semaphore gets unlocked.
The piece of code which accesses the shared resource is generally termed as the critical region.

Any process holding a semaphore,when it is releasing the shared resource also has to release the semaphore by calling the function "signal" on that semaphore, thus enabling other functions waiting for the same semaphore to lock it and enter the critical section.

The internal working of a mutex, or binary semaphore is very simple. Every mutex is initially set to a integer value 1, which signifies that the mutex is in unlocked state. When a process calls the function wait on the mutex, the value of the semaphore is decremented by 1,thus making it 0. When the next process calls wait on the same mutex, the decrement of 1 from 0 will make the value negative, which will indicate to the process that the semaphore is not free and thus it can not enter the critical section. The process will increment the value back to 0 and then go into a wait or sleep state.

When a process calls the function signal on a mutex the value of the semaphore is incremented by 1, i.e. the value gets incremented to 1 from 0 making the semaphore available to other processes.

The following animation depicts the working of a binary semaphore.



In case of a counting semaphore the initial value of semaphore is set to the number of processes that are to be allowed into the critical section at the same time. If three processes need to be allowed into critical section then the initial value of semaphore will be set to three and each call of wait will decrement the value of semaphore by 1. Thus after three calls of wait, the value is semaphore would have reached 0 and any more calls to wait will make the number negative indicating the resource is busy.

Thus using semaphores we can successfully protect a critical section and restrict simultaneous access to a shared resource.

Follow by Email