Conditional Variable vs Semaphore

前端 未结 6 513
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-27 09:00

When should one use a semaphore and when should one use a conditional variable (CondVar) ?

6条回答
  •  情话喂你
    2020-11-27 09:43

    Let's reveal what's under the hood.

    Conditional variable is essentially a wait-queue, that supports blocking-wait and wakeup operations, i.e. you can put a thread into the wait-queue and set its state to BLOCK, and get a thread out from it and set its state to READY.

    Note that to use a conditional variable, two other elements are needed:

    • a condition (typically implemented by checking a flag or a counter)
    • a mutex that protects the condition

    The protocol then becomes,

    1. acquire mutex
    2. check condition
    3. block and release mutex if condition is true, else release mutex

    Semaphore is essentially a counter + a mutex + a wait queue. And it can be used as it is without external dependencies. You can use it either as a mutex or as a conditional variable.

    Therefore, semaphore can be treated as a more sophisticated structure than conditional variable, while the latter is more lightweight and flexible.

提交回复
热议问题