Subj : Re: proper order of pthread_mutex_unlock() and pthread_cond_signal() To : comp.programming.threads From : Eric Sosman Date : Mon Jan 31 2005 06:04 pm el_bandido@nospam.com wrote: > Hi, > > Consider following pseudo-code: > > void foo() { > pthread_mutex_lock(&mux); > while (in_use == 0) { > pthread_cond_wait(&cond, &mux); > } > in_use=0; > pthread_mutex_unlock(&mux); > pthread_cond_signal(&cond); > } > > I've read that pthread_cond_signal(&cond) should actually be inside the > locked code segment (critical section) and not outside as shown in the > example above. Any comments on why one of the correct solutions is the > way to go? Both work for me but I'm quite confident that one is wrong. It is said that signalling with the mutex lock can lead to "more predictable scheduling behavior." Consider a scenario where thread A signals while thread B is parked in cond_wait, but thread C is also interested in the same mutex. If A unlocks and then signals, C may re-lock the mutex and perhaps change the predicate before B can awaken. If A signals and then unlocks this can still happen, but may be less likely. However, a program that depends so sensitively on the vagaries of thread scheduling is suspect to begin with: why should you care whether B gets its chance before or after C? Or, if you do care, why aren't you doing something explicit about it instead of relying on fiddly implementation details? If the exact ordering of B and C is unimportant or is being handled in some other way, then it seems to me that another principle should rule: Keep critical regions as short as is practical, that is, hold locks for the least time you can comfortably manage. This principle suggests that unlocking and then signalling is preferable: cond_signal doesn't need mutex protection, hence cond_signal can be moved outside the critical section, hence it *should* be outside. Neither arrangement is "right" or "wrong," but I think it is usually better to unlock first and signal afterward. Of course, if the program requires a particular ordering of B and C and hasn't taken other steps to enforce it, the program is already broken beyond the power of a simple rearrangement to repair it. -- Eric.Sosman@sun.com .