多个pthread_cond_wait唤醒并保持互斥锁

时间:2011-07-24 09:15:07

标签: multithreading pthreads

根据手册页, pthread_cond_broadcast 唤醒正在等待条件变量(condvar)的所有线程。那些被唤醒的线程将阻止互斥锁并从 pthread_cond_wait 返回。

但令我困惑的是:是不是互斥锁只能同时由一个线程持有?

提前致谢。

1 个答案:

答案 0 :(得分:2)

条件变量的工作方式如下:

/* 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);

所以要理解的要点是,许多线程可以在发送广播时唤醒,但只有一个会“赢”比赛并实际锁定mtx并退出循环。