I was looking at this article about conditon_variables. http://www.justsoftwaresolutions.co.uk/threading/condition-variable-spurious... For a timeout, the article has the following sample program with condition variables. template<typename Duration> bool timed_wait_and_pop(Data& popped_value, Duration const& wait_duration) { boost::system_time const timeout=boost::get_system_time()+wait_duration; boost::mutex::scoped_lock lock(the_mutex); while(the_queue.empty()) { if(!the_condition_variable.timed_wait(lock,timeout)) return false; } popped_value=the_queue.front(); the_queue.pop(); return true; } However, shouldn't this program instead start with boost::mutex::scoped_lock lock(the_mutex, timeout); if(!lock.owns()) return false; i.e. shouldn't it also take care of getting stuck while locking the mutex. i.e. if the timeout is 5 seconds & the getting the lock itself takes 10 seconds, then, the earlier the program will return is 10+ seconds.
"Just C" wrote:
I was looking at this article about conditon_variables. http://www.justsoftwaresolutions.co.uk/threading/condition-variable-spurious...
For a timeout, the article has the following sample program with condition variables.
...
However, shouldn't this program instead start with
boost::mutex::scoped_lock lock(the_mutex, timeout); if(!lock.owns()) return false;
i.e. shouldn't it also take care of getting stuck while locking the mutex.
i.e. if the timeout is 5 seconds & the getting the lock itself takes 10 seconds, then, the earlier the program will return is 10+ seconds.
In principle, yes. But in practice this should only matter in realtime code that needs to guarantee a response within the timeout period (which is typically measured in milliseconds or microseconds). Mutexes should never stay locked for 10 seconds in a correctly designed program - they should protect short critical sections. (Unless there is a deadlock, of course, in which case a timed mutex might help you detect it.) There is also the practical consideration that not all platforms support timed mutexes (in POSIX they are part of the realtime option, IIRC). When this is the case, a timed mutex is emulated with an ordinary mutex and a condition variable, so you will not be gaining much from it.
participants (2)
-
Just C
-
Peter Dimov