pthreads mutex vs semaphore

后端 未结 9 1101
旧巷少年郎
旧巷少年郎 2020-12-12 11:31

What is the difference between semaphores and mutex provided by pthread library ?

9条回答
  •  旧巷少年郎
    2020-12-12 12:12

    The difference between the semaphore and mutex is the difference between mechanism and pattern. The difference is in their purpose (intent)and how they work(behavioral).

    The mutex, barrier, pipeline are parallel programming patterns. Mutex is used(intended) to protect a critical section and ensure mutual exclusion. Barrier makes the agents(thread/process) keep waiting for each other.

    One of the feature(behavior) of mutex pattern is that only allowed agent(s)(process or thread) can enter a critical section and only that agent(s) can voluntarily get out of that.

    There are cases when mutex allows single agent at a time. There are cases where it allows multiple agents(multiple readers) and disallow some other agents(writers).

    The semaphore is a mechanism that can be used(intended) to implement different patterns. It is(behavior) generally a flag(possibly protected by mutual exclusion). (One interesting fact is even mutex pattern can be used to implement semaphore).

    In popular culture, semaphores are mechanisms provided by kernels, and mutexes are provided by user-space library.

    Note, there are misconceptions about semaphores and mutexes. It says that semaphores are used for synchronization. And mutexes has ownership. This is due to popular OS books. But the truth is all the mutexes, semaphores and barriers are used for synchronization. The intent of mutex is not ownership but mutual exclusion. This misconception gave the rise of popular interview question asking the difference of the mutexes and binary-semaphores.

    Summary,

    intent
    • mutex, mutual exclusion
    • semaphore, implement parallel design patterns
    behavior
    • mutex, only the allowed agent(s) enters critical section and only it(they) can exit
    • semaphore, enter if the flag says go, otherwise wait until someone changes the flag

    In design perspective, mutex is more like state-pattern where the algorithm that is selected by the state can change the state. The binary-semaphore is more like strategy-pattern where the external algorithm can change the state and eventually the algorithm/strategy selected to run.

提交回复
热议问题