2016-05-02 15 views
0

条件を関数内に入れようとしていますが、コンパイル時にエラーが混乱しています。私がこの[] {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()はブール値を返す呼び出し可能単項関数である述語を取ります。そうLIKE述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