条件变量 - 为什么调用调用调用pthread_cond_wait(之前调用pthread_cond_signal())是一个逻辑上的错误? [英] condition variable - why calling pthread_cond_signal() before calling pthread_cond_wait() is a logical error?

查看:171
本文介绍了条件变量 - 为什么调用调用调用pthread_cond_wait(之前调用pthread_cond_signal())是一个逻辑上的错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是写在POSIX线程教程
<一href=\"https://computing.llnl.gov/tutorials/pthreads/\">https://computing.llnl.gov/tutorials/pthreads/
它是一个逻辑上的错误。

It's written in POSIX threads tutorial https://computing.llnl.gov/tutorials/pthreads/ that it is a logical error.

我的问题是,为什么它是一个逻辑上的错误?

my question is why it is a logical error?

在我的节目,我需要使用这些信号,但是我不能保证会有一个线程,将在_cond_wait状态。我试图测试,并没有任何反应。难道这可能会导致意外的行为还是坏?

In my program i need to use these signals, however i cannot guarantee that there will be a thread that will be in _cond_wait state. I tried to test it and nothing happens. Is this can cause unexpected behavior or worse?

谢谢!

推荐答案

杀出的答案最接近的,但也不是完全清楚的:结果
条件变量应该只用于信号的条件的变化

The answer of blaze comes closest, but is not totally clear:
conditional variables should only be used to signal a change in a condition.

主题1检查的条件。如果条件不符合,他等待条件变量,直到该条件满足。由于条件首先检查,他不应该关心的条件变量是否信号:

Thread 1 checks a condition. If the condition doesn't meet, he waits on the condition variable until the condition meets. Because the condition is checked first, he shouldn't care whether the condition variable was signaled:

pthread_mutex_lock(&mutex); 
while (!condition)
    pthread_cond_wait(&cond, &mutex); 
pthread_mutex_unlock(&mutex);

主题2更改条件和信号通过条件变量的变化。他不在乎是否线程正在等待与否:

Thread 2 changes the condition and signals the change via the condition variable. He doesn't care whether threads are waiting or not:

pthread_mutex_lock(&mutex); 
changeCondition(); 
pthread_mutex_unlock(&mutex); 
pthread_cond_signal(&cond)

底线是:的通信是通过一定条件下完成的。条件变量只是唤醒等待的线程,使他们能够检查车况

有关条件的例子:


  • 队列不是空的,所以一个部件可以从队列可采取

  • 一个布尔标志设置,因此线程等待,直到小号其他线程的信号也没关系继续

  • 在一个bitset某些位被置位,所以等待的线程可以处理相应的事件

又见 PTHREAD例如

这篇关于条件变量 - 为什么调用调用调用pthread_cond_wait(之前调用pthread_cond_signal())是一个逻辑上的错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆