先决条件 – 进程同步
1. 二进制信号量:
二进制信号量是只能假定值 0 和 1 的信号量。它们用于通过使用信号机制实现互斥来实现锁。
这里,如果 semaphore 的值为 0 表示它被锁定,因此锁定不可用。
如果 semaphore 的值为 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. |