如何使用 boost 条件变量等待线程完成处理?
我正在使用一个条件变量来停止一个线程,直到另一个线程完成处理它的任务队列(长话短说).所以,在一个线程上我锁定并等待:
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();
我看到的问题是等待线程不会停止等待,除非我在它后面的指令上设置断点(我使用的是 xcode,仅供参考).是的,这看起来很奇怪.有谁知道为什么会发生这种情况?我是否误用了条件变量?
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()
的线程实际上在调用 wait()
的线程开始之前完成.(或者至少,notify_one()
调用发生在 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==true
在另一个线程开始等待之前,那么您将直接通过 while 循环而无需调用 wait()
.
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()
.
这种模式非常普遍,以至于我几乎可以说,如果您没有 while
循环包装您的 condition_variable.wait()
那么你总是有一个错误.事实上,当 C++11 采用类似于 boost::condtion_variable 的东西时,他们添加了一种新的 wait() ,它采用谓词 lambda 表达式(本质上它为您执行 while
循环):
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;});
相关文章