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


当前回答

“二进制信号量”是一种编程语言规避使用«信号量»,如«互斥量»。显然有两个非常大的区别:

你称呼他们的方式。 标识符的最大长度。

其他回答

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

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

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

除了互斥对象有一个所有者之外,这两个对象还可以针对不同的用途进行优化。互斥锁被设计为只保留很短的时间;违反这一点会导致糟糕的性能和不公平的调度。例如,一个正在运行的线程可能被允许获取一个互斥量,即使另一个线程已经被阻塞在这个线程上。信号量可以提供更多的公平性,或者可以使用几个条件变量强制实现公平性。

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

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

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

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

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

例如,你可以在互斥锁中启用错误检查属性。错误检查互斥量返回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:成功执行等待的进程必须执行一个信号,反之亦然。二进制信号量:不同的进程可以在一个信号量上执行等待或信号操作。