Question about cv_signal(9)

John Polstra jdp at polstra.com
Sat Jun 12 20:55:21 GMT 2004


I have a question about cv_signal(9).  As you know, cv_wait(9) is
passed a mutex which the caller must hold at the time of the call.  So
far, so good.  But I see from the man page and from asserts in the
code that this same mutex must be held when calling cv_signal.  That's
not required by other condition variable implementations I've seen
(for example: POSIX threads and Modula-3 threads), and I'm wondering
whether it's really necessary in the FreeBSD kernel's implementation.

The requirement is bad because it eliminates the simplest and most
common optimization that users of condition variables can take
advantage of.  Consider some typical wakeup code consistent with the
requirement that the mutex be held:

    mtx_lock(mutex);
    if (we want to signal the waiter) {
        set some shared state variables;
        cv_signal(cv);
    }
    mtx_unlock(mutex);

When cv_signal is called, the waiter will wake up and cv_wait() will
immediately try to re-acquire the mutex.  But the caller of cv_signal
still holds the mutex, so the waiter will again block until the waker
gets around to executing mtx_unlock(mutex).  That's two context
switches for every wakeup.

The standard optimization looks like this:

    int wake_up;

    wake_up = 0;

    mtx_lock(mutex);
    if (we want to signal the waiter) {
        set some shared state variables;
        wake_up = 1;
    }
    mtx_unlock(mutex);

    if (wake_up)
        cv_signal(cv);

This requires only a single context switch per wakeup -- a big win.
But it's not allowed, according to the cv_signal(9) man page.

>From briefly looking at the implementation, I can't see why the mutex
has to be held by the caller of cv_signal.  It seems like this is an
arbitrary requirement.  If so, I'd like to eliminate it.

Comments?

John

PS - The optimization above and several others are described in "An
Introduction to Programming with Threads," by Andrew D. Birrell:

http://gatekeeper.dec.com/pub/DEC/SRC/research-reports/abstracts/src-rr-035.html


More information about the freebsd-smp mailing list