Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ condition_variable wait_for predicate in my class, std::thread <unresolved overloaded function type> error

I am trying to use a thread within my class, then the thread needs to use a condition_variable, and the condition variable will be blocked until a predicate be changed to true. The code looks like this:

class myThreadClass{
    bool bFlag;
    thread t ;
    mutex mtx;
    condition_variable cv;

    bool myPredicate(){
      return bFlag;
    }

    int myThreadFunction(int arg){
       while(true){
           unique_lock<mutex> lck(mtx);
           if(cv.wait_for(lck,std::chrono::milliseconds(3000),myPredicate)) //something wrong?  
                cout<<"print something...1"<<endl 
           else
                cout<<"print something...2"<<endl 
       }
    }

    void createThread(){
        t = thread(&myThreadClass::myThreadFunction,this,10);//this is ok
    }

} ;

This code on compilation throws an error saying:

unresolved overloaded function type in the line “wait_for”.

Then i try modify it to:

if(cv.wait_for(lck,std::chrono::milliseconds(3000),&myThreadClass::myPredicate))

But there is still an error.

like image 555
user3375009 Avatar asked Sep 19 '16 04:09

user3375009


1 Answers

The predicate needs to be callable without any context. You are trying to invoke this on a non-static class member, which requires an object on which to operate.

You can use a lambda function to capture the object's context and wrap the function call into a suitable type:

const std::chrono::milliseconds timeout( 3000 );
if( cv.wait_for( lck, timeout, [this]{ return myPredicate(); } ) )
    // ...

If you only created myPredicate because of the condition variable, you can do away with it and just use this:

if( cv.wait_for( lck, timeout, [this]{ return bFlag; } ) )
like image 138
paddy Avatar answered Oct 13 '22 00:10

paddy