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 02:36:49PM +0000, Sad Clouds wrote:
  | As far as Pthreads standards go, calling pthread_cond_signal() and
  | having the associated mutex unlocked is legal.
  | Below is what the standard says:
  |  "The pthread_cond_signal() or pthread_cond_broadcast() functions
  | may be called by a thread whether or not it currently owns the mutex
  | that threads calling pthread_cond_wait() or pthread_cond_timedwait()
  | have associated with the condition variable during their waits;
  | however, if predictable scheduling behaviour is required, then that
  | mutex is locked by the thread calling pthread_cond_signal() or
  | pthread_cond_broadcast()."
  | However reading NetBSD's man page, it suggests that having the mutex
  | unlocked might produce undefined results:
  |  "The same mutex must be held while calling pthread_cond_broadcast()
  | and pthread_cond_signal(). Neither function enforces this
  | requirement, but if the mutex is not held the resulting behaviour is
  | undefined."
  | 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.

AFAICT, the NetBSD manual page and/or the implementation are wrong
in this respect.

Based on my investigation on this topic recently, it is valid to call
pthread_cond_signal() (and _broadcast()) without the mutex held,
according to the POSIX standard and other implementations I've also
used (Linux 2.6, Darwin).
You'll get an unpredictable wakeup of the sleeping thread, and/or
possibly a spurious wakeup, so you need to retest the condition
after being awoken, but that should be it.

I think it's explained well here, in a post quoting from
Butenhof's "Programming with POSIX Threads":

The most recent POSIX standard (1003.1-2008 issue 7) is at:

On a related note, I haven't yet checked if NetBSD's pthread_cond_wait()
returns EPERM on an unlocked mutex when used with a PTHREAD_MUTEX_ERRORCHECK
mutex.  Linux 2.6 does the right thing, Darwin 10.5 does not.


Attachment: pgptjLXd_VYJ1.pgp
Description: PGP signature

Home | Main Index | Thread Index | Old Index