开发者

Multile pthread_cond_wait waken up and hold the mutex lock

开发者 https://www.devze.com 2023-03-23 00:22 出处:网络
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 pthre

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

精彩评论

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

关注公众号