我试图添加一个condition_variable来处理线程,但在这一行得到一个编译错误:
this->cv.wait(lk, []{return this->ready;});
看起来对于变量this-> ready,'this'不在正确的范围内。
在Java中,可以使用TestThread来处理这个问题。在C ++中有什么做同样的事情吗?
void TestThread::Thread_Activity()
{
std::cout << "Thread started \n";
// Wait until ThreadA() sends data
{
std::unique_lock<std::mutex> lk(m);
this->cv.wait(lk, []{return ready;});
}
std::cout << "Thread is processing data\n";
data += " after processing";
// Send data back to ThreadA through the condition variable
{
// std::lock_guard<std::mutex> lk(m);
processed = true;
// std::cout << "Thread B signals data processing completed\n";
}
}
答案 0 :(得分:27)
您需要捕获this
指针:
this->cv.wait(lk, [this]{return ready;});