FOR FREE CONTENT

Semaphore Variable 

 

Now Dijkstra (1965) introduced the semaphore variable concept where the process not directly sends wakeup calls to the sleeping process, rather using an integer variable to count the number of wakeup calls saved for future use.  This special integer variable is called a semaphore.

 

When semaphore variables have a value of 0, indicating that no wakeup calls were saved. But if the semaphore variable contains a positive value i.e. one or more wakeup calls are pending.

 

But still semaphore variable can create a problem because a semaphore variable is a common or shared variable between two or more processes. We know common resources can create a problem like data-inconsistency or race condition.

 

To solve this problem Dijkstra proposed having two atomic actions (operations) on a semaphore, usually called down and up (generalizations of sleep and wakeup, respectively). By which only one process can access semaphore variable at a time. 

 

Semaphore: Variable on which read, modify and update happens atomically in kernel mode (no preemptive).

 

Semaphore can be used to implement mutual exclusion among any number of processes.

 

Down and Up operation

 

# Down operation perform an atomic action on a semaphore, checks to see if the value is greater than 0. If it is, it decrements by 1 and just continues. If the value is 0, the process is put to sleep without completing the down operation further.

 

# Similarly, the Up operation increments the value of the semaphore addressed. If one or more processes were sleeping on that semaphore, unable to complete an earlier down operation, one of them is chosen by the system (e.g., at random) and is allowed to complete it's down. Thus, after an up on a semaphore with processes sleeping on it, the semaphore will still be 0, but there will be one fewer process sleeping on it. 

The operation of incrementing the semaphore and waking up one process is also indivisible. No process ever blocks doing an up, just as no process ever blocks doing a wakeup in the earlier model.

 

# It is guaranteed that once a semaphore operation has started, no other process can access the semaphore until the operation has completed or blocked. This atomicity is absolutely essential to solving synchronization problems and avoiding race conditions.

 

Down and Up operation sometimes called P and V or Wait and Signal respectively.