thread: condition::notify() does not require a lock - why?
condition::wait requires that a lock is acquired prior to calling it, but condition::notify does not. The Java threading API (which in my limited experience seems similar to boost::thread) requires that a lock is acquired prior to calling Object.notify(). Is this potentially a problem? For example: scoped_lock myLock(myMutex); while (!some_variable) { // Another thread now sets some_variable = true, and // calls myCondition.notify() // then... // will this wait indefinitely? myCondition.wait(myLock); } Clearly if the other thread in this example were forced to obtain a lock on myMutex before calling myCondition.notify(), there would be no danger. In practice this is what I do anyway, but the boost:thread API doesn't force me to. Why not? Is there a potential problem if I don't? Many thanks...
The mutex ensures correctness even if not being held when the cond variable is signalled/broadcast AS LONG AS the "state" being waited on is only modified WHILE holding the mutex. Actually you typically get a little better performance if you are not holding the lock when you signal/broadcast on pthread systems because it can avoid a little thread ping-ponging over the mutex. On 25 Oct 2005, at 1:46 AM, Pete Chapman wrote:
condition::wait requires that a lock is acquired prior to calling it, but condition::notify does not. The Java threading API (which in my limited experience seems similar to boost::thread) requires that a lock is acquired prior to calling Object.notify().
Is this potentially a problem? For example:
scoped_lock myLock(myMutex); while (!some_variable) { // Another thread now sets some_variable = true, and // calls myCondition.notify() // then...
// will this wait indefinitely? myCondition.wait(myLock); }
Clearly if the other thread in this example were forced to obtain a lock on myMutex before calling myCondition.notify(), there would be no danger. In practice this is what I do anyway, but the boost:thread API doesn't force me to. Why not? Is there a potential problem if I don't?
Many thanks...
_______________________________________________ Boost-users mailing list Boost-users@lists.boost.org http://lists.boost.org/mailman/listinfo.cgi/boost-users
Thomas Costa wrote:
The mutex ensures correctness even if not being held when the cond variable is signalled/broadcast AS LONG AS the "state" being waited on is only modified WHILE holding the mutex.
Thanks, it all makes sense now. I also posted the question to comp.programming.threads and got some detailed responses. Apparently this sort of question comes up quite regularly... Thank you for the explanation.
participants (2)
-
Pete Chapman
-
Thomas Costa