
Yuval Ronen <ronen_yuval@yahoo.com> writes:
Scenario #1 ----------- 1. calls mutex_lock (kernel) 2. changes predicate 3. calls mutex_unlock (kernel) 4. calls cond_signal (kernel changes thread1 state from "blocked" to "ready"
Scenario #2 ----------- 1. calls mutex_lock (kernel) 2. changes predicate 3. calls cond_signal (kernel changes thread1 state from "blocked on cond" to "blocked on mutex" 4. calls mutex_unlock (kernel changes thread1 state from "blocked" to "ready"
Both scenarios contain exactly 3 kernel calls, and thread1 is made "ready" only after the 3rd call. No difference here.
Another thing (in addition to the better chance of avoiding bugs, as I explained in previous post) is that I believe that Scenario #2 better serves the "fairness" ideal, as described by Anthony Williams in http://lists.boost.org/Archives/boost/2006/10/112609.php. I'm not saying that RW mutex and CV are the same thing, but it might be that same principals apply to both.
If you look at the code attached to the message of mine that you've referenced, you will see that a) the code that does the notify already holds the mutex, since it has just changed the predicate. b) the code doesn't necessarily release the mutex immediately upon notifying the condition variable. In some circumstances, two condition variables are notified (one signalled, one broadcast) before the mutex is unlocked. c) if we release the mutex first, the state might have changed, and we might have additional threads waiting on the condition variables. Holding the mutex whilst we notify the CVs helps keep everything easy to follow. Point b) is where the "fairness" comes in --- there might be threads waiting on two CVs that we want to compete for the mutex. By holding the mutex whilst we notify both the CVs, we ensure the fairness. If we release the mutex first, then threads waiting on the CV we notify first effectively get priority over those waiting on the second CV. Anthony -- Anthony Williams Software Developer Just Software Solutions Ltd http://www.justsoftwaresolutions.co.uk