![](/img/trans.png)
[英]`std::condition_variable::wait_for` calls the predicate very often
[英]boost::condition_variable - using wait_for with predicate
我想等待一段時間的條件。 我讀了升壓文件和它似乎是最好使用功能wait_for
有謂語,如所描述這里 。
不幸的是,這個例子對我來說並不是很有用。 我該如何編寫謂詞? 我試着編寫上面報告的代碼,但是visual studio編譯器抱怨: c:\\boost\\boost\\thread\\win32\\condition_variable.hpp(394): error C2064: term does not evaluate to a function taking 0 arguments
這是代碼的一部分:
class MyClass{
boost::mutex mutex;
boost::condition_variable myCondition;
//...
void foo();
bool myPredicate();
}
void MyClass::foo(){
boost::unique_lock<boost::mutex> lock(mutex);
boost::chrono::microseconds period(25000);
// ...
boost::chrono::system_clock::time_point wakeUpTime = boost::chrono::system_clock::now() + period;
if(myCondition.wait_until(lock,wakeUpTime,MyClass::myPredicate) == true){/...}
}
bool MyClass::myPredicate(){
if(...)
return true;
else
return true;
}
將wait_for
與謂詞一起使用的正確方法是什么?
建議將wait
函數與謂詞一起使用,因為與手寫循環相比,它們不易出錯。 手寫循環可能如下所示:
for (;;) {
if (myPredicate()) {
// ... [successful case]
break;
} else if (myCondition.wait_until(lock, wakeUpTime) == boost::cv_status::timeout) {
// ... [timeout case]
break;
} // else: continue loop [spurious wakeup]
}
如果將謂詞傳遞給wait
函數,它可能是一個類似函數的東西,可以在沒有參數的情況下調用並返回一個可以用作bool
。 例如,您可以為此目的使用static
成員函數:
struct Foobar {
static bool isFoobar();
};
myCondition.wait_until(lock, wakeUpTime, Foobar::isFoobar);
您不能直接傳遞非靜態成員函數,因為它只能與對象一起調用。 但是,您可以使用函數對象:
struct MyPredicateWrapper {
MyClass* _ptr;
explicit MyPredicateWrapper(MyClass* ptr) : _ptr(ptr) { }
bool operator()() const { return _ptr->myPredicate(); }
};
myCondition.wait_until(lock, wakeUpTime, MyPredicateWrapper(this));
你可以用boost::bind
做同樣的事情:
myCondition.wait_until(lock, wakeUpTime, boost::bind(&MyClass::myPredicate, this));
如果您使用的是C ++ 11,還可以使用lambda函數 :
myCondition.wait_until(lock, wakeUpTime, [this] { return myPredicate(); });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.