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.
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; } ) )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With