我试图在我的类中使用一个线程,然后线程需要使用a condition_variable
,条件变量将被阻塞,直到谓词被更改为true
.代码如下所示:
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
}
} ;
Run Code Online (Sandbox Code Playgroud)
编译时的这段代码会抛出错误说:
"wait_for"行中未解决的重载函数类型.
然后我尝试将其修改为:
if(cv.wait_for(lck,std::chrono::milliseconds(3000),&myThreadClass::myPredicate))
Run Code Online (Sandbox Code Playgroud)
但仍然存在错误.