如何使用升压条件变量等待线程完成处理? [英] How do I use a boost condition variable to wait for a thread to complete processing?
问题描述
我使用的条件变量,直到另一个线程处理完它的任务队列(长的故事)来停止一个线程。因此,在一个线程我锁定和等待:
I am using a conditional variable to stop a thread until another thread has completed processing it's task queue (long story). So, on one thread I lock and wait:
boost::mutex::scoped_lock lock(m_mutex);
m_condition.wait(lock);
在另一个线程已经完成了它的任务,它标志着等待线程如下:
Once the other thread has completed it's tasks, it signals the waiting thread as follows:
boost::mutex::scoped_lock lock(m_parent.m_mutex);
m_parent.m_condition.notify_one();
我看到的问题是,除非我把它后面的指令断点(我用X code,仅供参考)等待线程不会停止等待。是的,这似乎很奇怪。没有人知道为什么这可能发生?上午我误使用条件变量?
The problem I am seeing is that the waiting thread does not stop waiting unless I set a breakpoint on the instructions following it (I am using xcode, fyi). Yes, this seems strange. Does anyone know why this might be happening? Am I mis-using the condition variable?
推荐答案
是的,你是滥用的条件变量。 条件变量都是真的只是信令机制。您还需要测试的条件。你的情况是什么可能发生的是,正在调用线程 notify_one()
调用线程等待()前实际完成
甚至开始。这就是所谓的(或者至少,在 notify_one()
呼叫在<$ C $ C>的wait()电话。之前发生的事情) 错过唤醒。
Yes, you are misusing the condition variable. "Condition variables" are really just the signaling mechanism. You also need to be testing a condition. In your case what might be happening is that the thread that is calling notify_one()
actually completes before the thread that calls wait()
even starts. (Or at least, the notify_one()
call is happening before the wait()
call.) This is called a "missed wakeup."
解决方案是真正有一个包含你所关心的条件变量:
The solution is to actually have a variable which contains the condition you care about:
bool worker_is_done=false;
boost::mutex::scoped_lock lock(m_mutex);
while (!worker_is_done) m_condition.wait(lock);
和
boost::mutex::scoped_lock lock(m_mutex);
worker_is_done = true;
m_condition.notify_one();
如果 worker_is_done ==真
其他线程甚至开始等待那么你会正好落在while循环而没有之前调用等待( )
。
If worker_is_done==true
before the other thread even starts waiting then you'll just fall right through the while loop without ever calling wait()
.
此模式是很常见的,我几乎走这么远说,如果你没有一个,而
循环包装你的 condition_variable.wait()
然后你总是有一个bug。事实上,当C ++ 11采用了类似于升压的东西:: condtion_variable他们增加了一种新的等待(的),需要一个predicate拉姆达前pression(基本上它的而
循环你):
This pattern is so common that I'd almost go so far as to say that if you don't have a while
loop wrapping your condition_variable.wait()
then you always have a bug. In fact, when C++11 adopted something similar to the boost::condtion_variable they added a new kind of wait() that takes a predicate lambda expression (essentially it does the while
loop for you):
std::condition_variable cv;
std::mutex m;
bool worker_is_done=false;
std::unique_lock<std::mutex> lk(m);
cv.wait(lk, []{return worker_is_done;});
这篇关于如何使用升压条件变量等待线程完成处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!