gpt4 book ai didi

对 pthread_cond_wait 的困惑

转载 作者:太空宇宙 更新时间:2023-11-04 04:34:18 26 4
gpt4 key购买 nike

关于下面的代码,我的理解是线程1抢锁,检查条件,解锁时钟,将自己置为休眠状态。之后,线程 2 申请相同的锁和增量计数,然后唤醒休眠线程。我的问题是现在的条件还是false,但是唤醒了休眠的线程,会发生什么?而且条件变量是一组线程,那么如果有很多线程同时执行代码怎么办,wait()如何处理这种情况呢?最后请说明这段代码的正确执行顺序,非常感谢!!!

thread 1:
pthread_mutex_lock(&mutex);
while (!condition)
pthread_cond_wait(&cond, &mutex);
/* do something that requires holding the mutex and condition is true */
pthread_mutex_unlock(&mutex);

thread2:
while(1){
pthread_mutex_lock(&mutex);
count++;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
}

最佳答案

My question is that the condition right now is still false, but it awakes the sleeping thread, what will happen?

这就是 pthread_cond_waitwhile 循环中的原因。它仅在 pthread_cond_wait 解锁并且条件为真时才退出 while 循环。

这正是 pthread_cond_wait man page 的内容需要做笔记。

When using condition variables there is always a Boolean predicate involving shared variables associated with each condition wait that is true if the thread should proceed. Spurious wakeups from the pthread_cond_timedwait() or pthread_cond_wait() functions may occur. Since the return from pthread_cond_timedwait() or pthread_cond_wait() does not imply anything about the value of this predicate, the predicate should be re-evaluated upon such return.

(强调我的)。

关于对 pthread_cond_wait 的困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32815029/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com