📜  信号量和条件变量之间的区别

📅  最后修改于: 2021-08-27 18:34:34             🧑  作者: Mango

1.信号量
信号量,顾名思义,基本上是一个包括计数器,进程等待列表并支持两种不同操作(即等待和信号)的对象。它的类型包括计数信号量和二进制信号量。它只是一个同步工具,可用于处理临界区问题。它提供了用于控制编程环境中对公共资源的访问的简单抽象。

2.条件变量:
顾名思义,条件变量只是一个同步原语,允许线程等待直到特定条件发生。它包括两个操作,即等待和信号。它仅允许在线程感兴趣的事件发生时向线程发出信号,并且通常在人们想知道何时发生事件时使用。

信号量和条件变量之间的区别:

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.