|
Boost : |
From: Yuval Ronen (ronen_yuval_at_[hidden])
Date: 2006-12-07 11:12:16
Peter Dimov wrote:
> Yuval Ronen wrote:
>> Peter Dimov wrote:
>>> Yuval Ronen wrote:
>>>> Hello.
>>>>
>>>> The Boost CV class forces that a mutex would be locked when calling
>>>> wait(), but not when calling notify(). This seems a bit strange to
>>>> me.
>>> It isn't strange since notify is typically not called with the mutex
>>> locked. This would cause the awakened thread to immediately be put
>>> back to sleep to wait for the mutex.
>> Yes, but what's the harm in that? The notify simply change the state
>> of the thread from "waiting on a CV" to "waiting on a mutex". I'm no
>> operating system expert, but I guess it can be done with a flip of a
>> flag (or two) inside the kernel. After that we continue normally.
>
> It can be done in principle, but then you still need to make another kernel
> call in unlock to wake up the thread that you already tried to wake up in
> notify. If the unlock is done before the notify, it can take the fast path
> and not enter the kernel (unless there's someone else waiting on the mutex).
Ok, while trying to understand this, I made a list of kernel calls in
each scenario. Both scenarios contain two threads: Thread1 is waiting on
a CV. Thread2 locks the mutex (as it should), changes the CV predicate,
notifies the CV, and unlock the mutex, either before or after the
notify. Lets see what Thread2 does:
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. Or maybe you disagree with what Anthony wrote?
Ignore this paragraph if so...
Yuval
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk