二进制信号量和互斥量之间有区别吗?或者它们本质上是相同的?


当前回答

互斥锁只能由获得它的线程释放。 二进制信号量可以由任何线程(或进程)发出信号。

因此,信号量更适合于一些同步问题,如生产者-消费者。

在Windows上,二进制信号量更像事件对象而不是互斥对象。

其他回答

最好的解决方案

唯一的区别是

1.互斥锁-> lock和unlock属于锁定互斥锁的线程。

2.信号量->没有所有权,即;如果一个线程调用semwait(s),任何其他线程都可以调用sempost(s)来移除锁。

互斥锁用于阻塞关键区域,而信号量用于计数。

Mutex is used to protect the sensitive code and data, semaphore is used to synchronization.You also can have practical use with protect the sensitive code, but there might be a risk that release the protection by the other thread by operation V.So The main difference between bi-semaphore and mutex is the ownership.For instance by toilet , Mutex is like that one can enter the toilet and lock the door, no one else can enter until the man get out, bi-semaphore is like that one can enter the toilet and lock the door, but someone else could enter by asking the administrator to open the door, it's ridiculous.

在窗口,差异如下所示。 MUTEX:成功执行等待的进程必须执行一个信号,反之亦然。二进制信号量:不同的进程可以在一个信号量上执行等待或信号操作。

它们的同步语义非常不同:

互斥对象允许对给定资源的序列化访问,即多个线程等待一个锁,一次一个,正如前面所说,线程拥有锁,直到锁完成:只有这个特定的线程可以解锁它。 二进制信号量是一个值为0和1的计数器:任务阻塞在它上,直到任何任务执行sem_post。信号量宣布资源可用,并提供等待机制,直到发出可用信号。

因此,可以将互斥锁视为在任务之间传递的令牌,将信号量视为交通红灯(它向某人发出信号,表示可以继续进行)。