为什么有了信号量还需要条件锁

SO上的一个问题:

pthread_cond_wait versus semaphore

一个回答:

Conditionals let you do some things that semaphores won't.

For example, suppose you have some code which requires a mutex, called m. It however needs to wait until some other thread has finish their task, so it waits on a semaphore called s. Now any thread which needs m is blocked from running, even though the thread which has m is waiting on s. These kind of situations can be resolved using conditionals. When you wait on a conditional, the mutex currently held is released, so other threads can acquire the mutex. So back to our example, and suppose conditional c was used instead of s. Our thread now acquires m, and then conditional waits on c. This releases m so other threads can proceed. When c becomes available, m is reacquired, and our original thread can continue merrily along its way.

Conditional variables also allows you to let all threads waiting on a conditional variable to proceed via pthread_cond_broadcast. Additionally it also allows you to perform a timed wait so you don't end up waiting forever.

Of course, sometimes you don't need conditional variables, so depending on your requirements, one or the other may be better.

posted @ 2019-12-29 15:06  相印  阅读(387)  评论(0)    收藏  举报