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


当前回答

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部分:信号量 互斥量与信号量——第2部分:互斥量 互斥量与信号量——第3部分(最后一部分):互斥问题

来自第二部分:

The mutex is similar to the principles of the binary semaphore with one significant difference: the principle of ownership. Ownership is the simple concept that when a task locks (acquires) a mutex only it can unlock (release) it. If a task tries to unlock a mutex it hasn’t locked (thus doesn’t own) then an error condition is encountered and, most importantly, the mutex is not unlocked. If the mutual exclusion object doesn't have ownership then, irrelevant of what it is called, it is not a mutex.

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

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

互斥量和二进制信号量是相同的用法,但实际上,它们是不同的。

对于互斥锁,只有锁定了它的线程才能解锁它。如果有其他线程来锁定它,它将等待。

对于信号电话来说,情况就不是这样了。信号量没有与特定的线程ID绑定。

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.