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.
if (cv.wait_for(lck, std::chrono::milliseconds(3000), [this]{ return myPredicate(); }))
– Libau