pthreads mutex vs semaphore

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

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

相关标签:
9条回答
  • 2020-12-12 12:08

    semaphores have a synchronized counter and mutex's are just binary (true / false).

    A semaphore is often used as a definitive mechanism for answering how many elements of a resource are in use -- e.g., an object that represents n worker threads might use a semaphore to count how many worker threads are available.

    Truth is you can represent a semaphore by an INT that is synchronized by a mutex.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-12 12:14

    This two articles explain great details about mutex vs semaphores Also this stack overflow answer tells the similar answer.

    0 讨论(0)
提交回复
热议问题