tech-userlevel archive
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index][Old Index]
Re: pthread_cond_signal() ambiguity
On Wed, Dec 02, 2009 at 04:40:40PM +0100, Jean-Yves Migeon wrote:
> > Now my question is: does anyone think that NetBSD's
> > implementation of pthread_cond_signal() is broken? I think quite
> > a few people intentionally unlock the mutex before calling
> > pthread_cond_signal(), so that the thread that wakes up can lock
> > this mutex asap. and start running, instead of blocking.
>
> Or wait forever, as it will race against the pthread_cond_signal: thread A
> acquires the mutex, check condition, but thread B signals a condition
> change between A wait for it; as B did not acquire the mutex, thread A
> might not see the signal.
This cannot happen. In order to actually change the condition, B has
to hold the mutex. It doesn't matter when B signals the change as long
as it's not *before* it changes the condition. (But that would be a
crazy thing to do, so it's not worth thinking about.)
If A comes along before B changes the condition, A will go to sleep,
then B will change the condition, then B will signal, then A will wake
up. If A comes along after B changes the condition, it won't sleep and
it doesn't matter when B signals. And if A is already sleeping, it
doesn't matter at all.
It is essential for the action "A releases the mutex and goes to
sleep" to be atomic, but that's true regardless. This reasoning also
assumes that the condition is being tested in a loop, but that's also
necessary in general. (There are cases in which one can write code
that doesn't require a loop, even if the condition variable doesn't
provide Hoare semantics, but such code is fundamentally hackish and
should be avoided.)
Whether it's worth specifically releasing the mutex first as an
"optimization" is a separate question entirely, and I'd guess the
answer is no.
--
David A. Holland
dholland%netbsd.org@localhost
Home |
Main Index |
Thread Index |
Old Index