lundi 2 mai 2016

Issue in predicate function in wait in thread C++

I am trying to put the condition inside a function but it is throwing confusing compile time error . While if I write it in lambda function like this []{ retur i == k;} it is showing k is unidentified . Can anybody tell How to solve this problem .

#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;
}

Compiler Error:

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

Aucun commentaire:

Enregistrer un commentaire