What is the difference between semaphore and mutex

2019-05-05 16:54发布

问题:

I read that mutex and binary semaphore are different in only one aspect, in the case of mutex the locking thread has to unlock, but in semaphore the locking and unlocking thread can be different?

Which one is more efficient?

回答1:

Assuming you know the basic differences between a sempahore and mutex :

For fast, simple synchronization, use a critical section.

To synchronize threads across process boundaries, use mutexes.

To synchronize access to limited resources, use a semaphore.

Apart from the fact that mutexes have an owner, the two objects may be optimized for different usage. Mutexes are designed to be held only for a short time; violating this can cause poor performance and unfair scheduling. For example, a running thread may be permitted to acquire a mutex, even though another thread is already blocked on it, creating a deadlock. Semaphores may provide more fairness, or fairness can be forced using several condition variables.