Advantages of using condition variables over mutex

前端 未结 3 2210
陌清茗
陌清茗 2020-12-22 19:58

I was wondering what is the performance benefit of using condition variables over mutex locks in pthreads.

What I found is : \"Without condition variables, the prog

3条回答
  •  执念已碎
    2020-12-22 20:05

    A condition variable allows a thread to be signaled when something of interest to that thread occurs.

    By itself, a mutex doesn't do this.

    If you just need mutual exclusion, then condition variables don't do anything for you. However, if you need to know when something happens, then condition variables can help.

    For example, if you have a queue of items to work on, you'll have a mutex to ensure the queue's internals are consistent when accessed by the various producer and consumer threads. However, when the queue is empty, how will a consumer thread know when something is in there for it to work on? Without something like a condition variable it would need to poll the queue, taking and releasing the mutex on each poll (otherwise a producer thread could never put something on the queue).

    Using a condition variable lets the consumer find that when the queue is empty it can just wait on the condition variable indicating that the queue has had something put into it. No polling - that thread does nothing until a producer puts something in the queue, then signals the condition that the queue has a new item.

提交回复
热议问题