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


当前回答

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

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

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

其他回答

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

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

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

http://www.geeksforgeeks.org/archives/9102将详细讨论。

互斥是一种锁机制,用于同步对资源的访问。 信号量是一种信号机制。

如果他/她想使用二进制信号量来代替互斥量,这取决于程序员。

The basic issue is concurrency. There is more than one flow of control. Think about two processes using a shared memory. Now only one process can access the shared memory at a time. If more than one process accesses the shared memory at a time, the contents of shared memory would get corrupted. It is like a railroad track. Only one train can run on it, else there would be an accident.So there is a signalling mechanism, which a driver checks. If the signal is green, the train can go and if it is red it has to wait to use the track. Similarly in case of shared memory, there is a binary semaphore. If the semaphore is 1, a process acquires it (makes it 0) and goes ahead and accesses it. If the semaphore is 0, the process waits. The functionality the binary semaphore has to provide is mutual exclusion (or mutex, in short) so that only one of the many concurrent entities (process or thread) mutually excludes others. It is a plus that we have counting semaphores, which help in synchronizing multiple instances of a resource.

互斥是信号量提供的基本功能。现在在线程上下文中,我们可能有不同的名称和语法。但基本概念是相同的:如何在并发编程中保持代码和数据的完整性。在我看来,像所有权和相关检查这样的东西是由实现提供的改进。

最好的解决方案

唯一的区别是

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

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

互斥锁:假设我们有临界区线程T1想要访问它,然后按照以下步骤进行。 T1:

锁 使用临界区 解锁

二进制信号量:它基于信号等待和信号工作。 等待将“s”的值减少1,通常“s”的值初始化为值“1”, 信号(s)使“s”值加1。如果“s”值为1表示没有人在使用临界区,当“s”值为0时表示临界区正在使用。 假设线程T2正在使用临界区,那么它遵循以下步骤。 T2:

Wait (s)//最初的s值是1,调用Wait后,它的值减少了1,即0 利用临界区 信号(s) //现在s值增加,变成1

Main difference between Mutex and Binary semaphore is in Mutext if thread lock the critical section then it has to unlock critical section no other thread can unlock it, but in case of Binary semaphore if one thread locks critical section using wait(s) function then value of s become "0" and no one can access it until value of "s" become 1 but suppose some other thread calls signal(s) then value of "s" become 1 and it allows other function to use critical section. hence in Binary semaphore thread doesn't have ownership.