2016-05-02 24 views
0

我试图把条件放入一个函数中,但它引发了令人困惑的编译时错误。虽然如果我用这样的lambda函数写它[] {retur i == k;}它显示k是不明的。任何人都可以告诉如何解决这个问题。在线程中的等待中的谓词函数中的问题C++

#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()) 
      ^

回答

2

wait()需要谓词,这是一个可调用一元函数返回布尔。 wait()使用了谓词像这样:

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

check_func(i,k)bool。这是不可回调的,这是一个常数 - 这打破了目的。你在等待一些可以改变的东西。你需要用它的东西,可以反复调用 - 就像一个拉姆达:

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

要澄清一点,它不是一个真正的常量 - 这是计算结果为布尔值的表达式,该值是什么被传递给'wait'(不是函数本身)。 – Cameron

+0

我相信check_func之前应该有return关键字。之后,它不会导致任何编译时错误。但在此之后,它正在被吊死,并导致超过时间限制,并没有打印任何东西? – user3798283

+0

@user好吧,你所有的线程都在等待发生的事情永远不会发生。这是一个编程逻辑错误。 – Barry