Does someone have an example of how to most easily use boost::condition::timed_wait? There are some threads on the topic here, here and here, but none feature a working example. And boost doc is as usual quite sparse.
Asked
Active
Viewed 3.1k times
18
-
This seems well documented in boost and a timed wait on a condition variable is very common in a multithreaded environment. What specifically are you looking for help with? – Chad Aug 16 '11 at 13:50
-
4@Chad: Maybe I just missed the doc? All I found was [here](http://www.boost.org/doc/libs/1_47_0/doc/html/thread/synchronization.html#thread.synchronization.condvar_ref). That only contains an non timed sample, namely `while(!data_ready) { cond.wait(lock); }`. For timed, it only says _The duration overload of timed_wait is difficult to use correctly. The overload taking a predicate should be preferred in most cases._ I don't understand that though, nor this snippet: `while(!pred()) { if(!timed_wait(lock,abs_time)) { return pred(); } } return true;` What is pred() supposed to be? – Cookie Aug 16 '11 at 14:18
1 Answers
23
Actually, I finally found a link with full example here. With a bit of adapting, this seems to be the call.
boost::system_time const timeout=boost::get_system_time()+ boost::posix_time::milliseconds(35000);
boost::mutex::scoped_lock lock(the_mutex);
if(the_condition_variable.timed_wait(lock,timeout,&CondFulfilled))
{
<cond fulfilled code>
}
else
{
<timeout code>
}
bool CondFulfilled() { ... }

Cookie
- 12,004
- 13
- 54
- 83