开发者

Multile pthread_cond_wait waken up and hold the mutex lock

According to the man page, pthread_cond_broadcast wakes up all the threads that are waiting on condition variable (condvar). And those waken threads will hold back the mutex lock and return from pthread_cond_wait.

But what I am confusing is: Isn't it the mutex lock should held by only one thread in the same time开发者_开发知识库?

Thanks in advance.


Condition variables work like this:

/* Lock a mutex. */
pthread_mutex_lock(&mtx);

/* Wait on condition variable. */
while (/* condition *.)
    pthread_cond_wait(&cond, &mtx);

/* When pthread_cond_wait returns mtx is atomically locked. */

/* ... */

/* Unlock the mutex. */
pthread_mutex_unlock(&mtx);

So the main point to understand is that many threads can wake up when a broadcast is sent, but only one will "win" the race and actually lock mtx and get out of the loop.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜