📜  Binary Semaphore和Mutex之间的区别

📅  最后修改于: 2021-08-25 17:50:58             🧑  作者: Mango

先决条件–流程同步

1.二进制信号量:
二进制信号量是只能假定值为0和1的信号量。它们用于通过使用信号机制实现互斥来实现锁。

在这里,如果信号量的值为0,则意味着它已被锁定,因此锁定不可用。
如果信号量的值为1,则表示它已解锁,因此可以使用锁定。

2.互斥体:
互斥锁提供互斥,生产者或使用者都可以拥有密钥(互斥锁)并继续其工作。只要生产者填充了缓冲区,消费者就需要等待,反之亦然。

在任何时间点,只有一个线程可以使用整个缓冲区。可以使用信号量来概括该概念。

二进制信号量和互斥量之间的区别:

Binary Semaphore Mutex
Its functions based up on signalling mechanism Its functions based up on locking mechanism
The thread which is having higher priority than current thread can also release binary semaphore and take lock. The thread which has acquired mutex can only release Mutex when it exits from critical section.
Semaphore value is changed according to wait () and signal () operations. Mutex values can be modified just as locked or unlocked.
Multiple number of threads can acquire binary semaphore at a time concurrently. Only one thread can acquire mutex at a time
Binary semaphore have no ownership. There is ownership associated with mutex because only owner can release the lock.
They are faster than mutex because any other thread/process can unlock binary semaphore. They are slower than binary semaphores because only thread which has acquired must release the lock.
If you have number of instances for resource it is better to use Binary semaphore. If you have single instance for resource it is better to use mutex.