【问题标题】:Multile pthread_cond_wait waken up and hold the mutex lock多个 pthread_cond_wait 被唤醒并持有互斥锁
【发布时间】:2011-10-11 23:14:00
【问题描述】:

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

但我很困惑的是:互斥锁不应该只由一个线程同时持有吗?

提前致谢。

【问题讨论】:

    标签: multithreading pthreads


    【解决方案1】:

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

    /* 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并退出循环.

    【讨论】:

    • cnicutar: 这意味着只有 一个 线程将从 pthread_cond_wait() 返回,其他线程将保持阻塞状态。我说的对吗?
    • @Martin:要明确一点——一次只有一个线程会从pthread_cond_wait() 调用(持有互斥锁的那个)返回。释放互斥锁时,其他人将(一个接一个)返回。它们是否退出while 循环取决于条件是保持为真还是由第一个(或后续)线程变为假。
    猜你喜欢
    • 1970-01-01
    • 2010-11-22
    • 2017-04-21
    • 2012-12-14
    • 2011-09-12
    • 1970-01-01
    • 1970-01-01
    • 2013-02-02
    相关资源
    最近更新 更多