【问题标题】:About pthread_cond_wait关于 pthread_cond_wait
【发布时间】:2014-10-02 20:52:27
【问题描述】:

对于以下代码:

f1()
{
    pthread_mutex_lock(&mutex); //LINE1 (thread3 and thread4)
    pthread_cond_wait(&cond, &mutex);  //LINE2  (thread1 and thread2)
    pthread_mutex_unlock(&mutex); 
}

f2()
{
    pthread_mutex_lock(&mutex); 
    pthread_cond_signal(&cond);  //LINE3 (thread5)
    pthread_mutex_unlock(&mutex); 
}

假设 thread1 和 thread2 在 LINE2 等待,thread3 和 thread4 在 LINE1 被阻塞。当thread5执行LINE3时,哪些线程会先运行?线程1还是线程2?线程3还是线程4?

【问题讨论】:

    标签: pthreads


    【解决方案1】:

    当线程 5 发出条件信号时,线程 1 或线程 2 或两者都将从等待中释放,并等待互斥体可以被锁定...直到线程 5 解锁它之后。

    当 thread5 然后解锁互斥锁时,等待锁定互斥锁的线程之一将能够这样做。我对 POSIX 的阅读表明,等待锁定的线程将继续执行的顺序是“未定义的”,尽管更高优先级的线程可能会首先运行。事情的安排方式很大程度上取决于系统。

    如果您需要线程以特定顺序运行,那么您需要自己安排。

    【讨论】:

      猜你喜欢
      • 2017-01-08
      • 1970-01-01
      • 2017-05-07
      • 1970-01-01
      • 1970-01-01
      • 2019-08-08
      • 1970-01-01
      • 1970-01-01
      • 2012-03-18
      相关资源
      最近更新 更多