包含 pthread_cond_wait 的 while 循环的行为是什么?

What will be the behavior of a while loop that encloses pthread_cond_wait?

我想知道等待线程被唤醒后 while 会发生什么。

为了避免 'spurious wake-ups',pthreads 文档指出您需要在 while 语句中使用 pthread_cond_wait

因此,当 pthread_cond_wait 被调用时,调用线程被阻塞。发出信号后,线程在 while.

内恢复

在我的代码中,我是这样处理 pthread_cond_wait() 的:

pthread_mutex_lock(&waiting_call_lock);
while(1) {
    pthread_cond_wait(&queue_cond[thread_ctx], &waiting_call_lock);
    break;
}
pthread_mutex_unlock(&waiting_call_lock);

问题是,它会尝试再次进入 while 还是不知何故 break while 并继续?或者,在那种情况下,pthread_cond_wait() 之后的 break 是必要的吗?

要做到这一点,我认为最好先问问自己:"what is the thread waiting for?"

答案不应该是 "it should wait until another thread signals it",因为条件变量的工作方式是假设线程要等待的其他东西,某种 mutex-protected 信息。

为了说明这一点,我将在此处发明一个示例,其中线程应该等待,直到名为 counter 的变量大于 7。变量 counter 可由多个线程访问并受到保护通过一个我称之为 theMutex 的互斥锁。那么涉及 pthread_cond_wait 调用的代码可能如下所示:

pthread_mutex_lock(&theMutex);
while(counter <= 7) {
    pthread_cond_wait(&cond, &theMutex);
}
pthread_mutex_unlock(&theMutex);

现在,如果 "spurious wake-up" 发生,程序将再次检查条件 (counter <= 7),发现它仍然不满足,所以它会留在循环中并调用 pthread_cond_wait 再次。因此,这确保了线程在满足条件之前不会继续通过 while 循环。

由于虚假 wake-ups 在实践中很少发生,触发它以检查您的实施是否正常工作可能是有意义的;这里有一个讨论:How to trigger spurious wake-up within a Linux application?