Skip to content
Related Articles

Related Articles

Difference between Semaphore and Condition Variable
  • Last Updated : 23 Feb, 2021

1. Semaphore :
Semaphore, as name suggests, is basically an object that includes counter, waiting list of process and supports two different operations i.e., wait and signal. Its type includes counting semaphores and binary semaphores. It is simply a synchronization tool that can be used to deal with critical-section problem. It provides simple abstraction for controlling access to a common resource in programming environment.

2. Condition Variable :
Condition Variable, as name suggests, is simply a synchronization primitive that allows threads to wait until particular condition occurs. It includes two operations i.e., wait and signal. It just allows thread to be signaled when something of interest to that threads occurs and is mostly used when one wants to know when something happens.

Difference between Semaphore and Condition Variable :

Semaphore 

Condition Variable  



It does not allow threads to wait. Instead, each thread keeps running and last thread that will set semaphore value to zero will go to sleep.It allows threads to wait until particular condition occurs.  
It is generally used to solve problem of some critical sections in process synchronization.  It is generally used with mutex to signal changing states from one thread to another one.
Its main aim is to control access to common resource by multiple processes and avoid critical section problems in concurrent system like multitasking operating system. Its main aim is to support operations that wake one or wake all waiting threads.  
It can be used anywhere except in a monitor.  It can only be used in monitors.  
In this, wait () does not always block its caller.  In this, wait () usually blocks its caller always. 
They are sticky as they have memory and sem_post() will increment semaphore even if no one has called sem_wait(). They are non-sticky as signal () is not saved if there is no one waiting for signal ().  
It is simply a counter + mutex + wait queue.  It is simply a wait-queue.  
It can be used as a conditional variable and therefore is more lightweight and flexible.  It cannot be used as a semaphore and therefore is not flexible.  
In this, we cannot unlock all waiting threads in same instant using broadcast unlocking.  In this, we can unlock all waiting threads in same instant using broadcast unlocking.  
Signals are not lost event if there is nobody waiting on the queue.  Signals are lost if there is nobody waiting on the queue. 

 

  

 

My Personal Notes arrow_drop_up
Recommended Articles
Page :