user3798283
user3798283

Reputation: 467

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

Upvotes: 0

Views: 1657

Answers (1)

Barry
Barry

Reputation: 302852

wait() takes a predicate, which is a callable unary function returning bool. wait() uses that predicate like so:

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

check_func(i,k) is a bool. It's not callable and it's a constant - which defeats the purpose. You're waiting on something that can change. You need to wrap it in something that can be repeatedly callable - like a lambda:

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

Upvotes: 3

Related Questions