Usage example of boost::condition::timed_wait
Asked Answered
O

1

18

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.

Otti answered 16/8, 2011 at 12:55 Comment(2)
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?Shoot
@Chad: Maybe I just missed the doc? All I found was here. 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?Otti
O
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() { ... }
Otti answered 16/8, 2011 at 14:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.