在线程C ++中等待谓词函数的问题

时间:2016-05-02 22:37:43

标签: multithreading c++11 mutex wait condition-variable

我试图将条件放在一个函数中,但它会引起令人困惑的编译时错误。虽然如果我在lambda函数中写这个[] {retur i == k;},它显示k是未识别的。任何人都可以告诉如何解决这个问题。

#include <iostream>
#include <mutex>
#include <sstream>
#include <thread>
#include <chrono>
#include <condition_variable>
using namespace std;
condition_variable cv;
mutex m;
int i;
bool check_func(int i,int k)
{
    return i == k;
}
void print(int k)
{
   unique_lock<mutex> lk(m);
   cv.wait(lk,check_func(i,k));            // Line 33
   cout<<"Thread no. "<<this_thread::get_id()<<" parameter "<<k<<"\n";
   i++;
   return;
}
int main() 
{
    thread threads[10];
    for(int i = 0; i < 10; i++)
       threads[i] = thread(print,i);
    for(auto &t : threads)
       t.join();
    return 0;
}

编译器错误:

In file included from 6:0:
/usr/include/c++/4.9/condition_variable: In instantiation of 'void std::condition_variable::wait(std::unique_lock<std::mutex>&, _Predicate) [with _Predicate = bool]':
33:30:   required from here
/usr/include/c++/4.9/condition_variable:97:14: error: '__p' cannot be used as a function
  while (!__p())
              ^

1 个答案:

答案 0 :(得分:2)

wait()接受一个谓词,这是一个可调用的一元函数返回bool。 wait()像这样使用该谓词:

while (!pred()) {
    wait(lock);
}

check_func(i,k)bool。它不可调用,而且它是常量 - 这会破坏目的。你在等待可以改变的事情。你需要将它包装在可以重复调用的东西中 - 比如lambda:

   cv.wait(lk, [&]{ return check_func(i,k); });