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


当前回答

互斥锁控制对单个共享资源的访问。它提供了获取()对资源的访问并在完成后释放()资源的操作。

信号量控制对共享资源池的访问。它提供Wait()操作,直到池中的一个资源可用,并提供Signal()操作,当它返回池时。

当一个信号量保护的资源数量大于1时,它被称为计数信号量。当它控制一个资源时,它被称为布尔信号量。布尔信号量相当于互斥量。

因此,信号量是比互斥量更高级别的抽象。互斥锁可以用信号量来实现,但不能用信号量来实现。

其他回答

互斥对象有所有权,不像信号量。尽管在互斥量范围内的任何线程都可以获得一个未锁定的互斥量,并锁定对同一关键代码段的访问,但只有锁定了互斥量的线程才应该解锁它。

虽然二进制信号量可以用作互斥量,但互斥量是一个更具体的用例,因为只有锁定了互斥量的进程才应该解锁它。这种所有权限制使我们有可能对以下情况提供保护:

意外释放 递归死锁 任务死亡死锁

这些限制并不总是存在,因为它们降低了速度。在代码开发期间,您可以暂时启用这些检查。

例如,你可以在互斥锁中启用错误检查属性。错误检查互斥量返回EDEADLK,如果你试图锁定同一个互斥量两次,如果你解锁了一个不是你的互斥量,返回EPERM。

pthread_mutex_t mutex;
pthread_mutexattr_t attr;
pthread_mutexattr_init (&attr);
pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_ERRORCHECK_NP);
pthread_mutex_init (&mutex, &attr);

一旦初始化,我们可以将这些检查放在我们的代码中,就像这样:

if(pthread_mutex_unlock(&mutex)==EPERM)
 printf("Unlock failed:Mutex not owned by this thread\n");

厕所的例子是一个有趣的类比:

Mutex: Is a key to a toilet. One person can have the key - occupy the toilet - at the time. When finished, the person gives (frees) the key to the next person in the queue. Officially: "Mutexes are typically used to serialise access to a section of re-entrant code that cannot be executed concurrently by more than one thread. A mutex object only allows one thread into a controlled section, forcing other threads which attempt to gain access to that section to wait until the first thread has exited from that section." Ref: Symbian Developer Library (A mutex is really a semaphore with value 1.) Semaphore: Is the number of free identical toilet keys. Example, say we have four toilets with identical locks and keys. The semaphore count - the count of keys - is set to 4 at beginning (all four toilets are free), then the count value is decremented as people are coming in. If all toilets are full, ie. there are no free keys left, the semaphore count is 0. Now, when eq. one person leaves the toilet, semaphore is increased to 1 (one free key), and given to the next person in the queue. Officially: "A semaphore restricts the number of simultaneous users of a shared resource up to a maximum number. Threads can request access to the resource (decrementing the semaphore), and can signal that they have finished using the resource (incrementing the semaphore)." Ref: Symbian Developer Library

最好的解决方案

唯一的区别是

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

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

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

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

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