Advantages of using condition variables over mutex

前端 未结 3 858
我寻月下人不归
我寻月下人不归 2020-12-22 19:22

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:25

    You're looking for too much overlap in two separate but related things: a mutex and a condition variable.

    A common implementation approach for a mutex is to use a flag and a queue. The flag indicates whether the mutex is held by anyone (a single-count semaphore would work too), and the queue tracks which threads are in line waiting to acquire the mutex exclusively.

    A condition variable is then implemented as another queue bolted onto that mutex. Threads that got in line to wait to acquire the mutex can—usually once they have acquired it—volunteer to get out of the front of the line and get into the condition queue instead. At this point, you have two separate sets of waiters:

    • Those waiting to acquire the mutex exclusively
    • Those waiting for the condition variable to be signaled

    When a thread holding the mutex exclusively signals the condition variable, for which we'll assume for now that it's a singular signal (unleashing no more than one waiting thread) and not a broadcast (unleashing all the waiting threads), the first thread in the condition variable queue gets shunted back over into the front (usually) of the mutex queue. Once the thread currently holding the mutex—usually the thread that signaled the condition variable—relinquishes the mutex, the next thread in the mutex queue can acquire it. That next thread in line will have been the one that was at the head of the condition variable queue.

    There are many complicated details that come into play, but this sketch should give you a feel for the structures and operations in play.

提交回复
热议问题