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

📅  最后修改于: 2021-09-15 01:25:47             🧑  作者: 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.