[英]c++ condition_variable wait_for predicate in my class, std::thread <unresolved overloaded function type> error
我试图在我的类中使用一个线程,然后线程需要使用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
}
} ;
编译时的这段代码会抛出错误说:
“wait_for”行中未解决的重载函数类型。
然后我尝试将其修改为:
if(cv.wait_for(lck,std::chrono::milliseconds(3000),&myThreadClass::myPredicate))
但仍然存在错误。
谓词需要在没有任何上下文的情况下可调用。 您试图在非静态类成员上调用它,这需要一个操作对象。
您可以使用lambda函数捕获对象的上下文,并将函数调用包装为合适的类型:
const std::chrono::milliseconds timeout( 3000 );
if( cv.wait_for( lck, timeout, [this]{ return myPredicate(); } ) )
// ...
如果你因为条件变量而只创建了myPredicate
,你可以取消它并使用它:
if( cv.wait_for( lck, timeout, [this]{ return bFlag; } ) )
一个(指向一个)成员函数作为谓词的指针是不合适的,因为它需要一个对象被调用,所以你需要一个包装器将成员函数绑定到一个对象并使它只用两个值来调用它比较。
在C ++ 11中,您可以将成员函数绑定到对象:
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),std::bind(&myThreadClass::myPredicate,this))) //something wrong?
cout<<"print something...1"<<endl;
else
cout<<"print something...2"<<endl;
}
}
void createThread(){
t = thread(&myThreadClass::myThreadFunction,this,10);//this is ok
}
};
你可以在bind中使用占位符。
或者你可以使用lambda函数。
是的,事实上最好的方法是..
auto myPredicate = [this]{ return bFlag; }
然后使用
if (cv.wait_for(lck, std::chrono::milliseconds(3000), myPredicate))
这样就可以消除myPrediate
方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.