Subj : Re: proper order of pthread_mutex_unlock() and pthread_cond_signal() To : comp.programming.threads From : el_bandido Date : Tue Feb 01 2005 12:47 am Hello Eric, > 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. Your explanation makes a lot of sense. > However, a program that depends so sensitively on the > vagaries of thread scheduling is suspect to begin with: Fully agreed. > 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. I think so too. > 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. Thank you very much for your excellent explanation, it all makes perfect sense. I was confused since I read the example code in the O'Reilly book "Pthreads Programming" written by Nichols, Buttlar and Farrell and they signal first and then unlock (p80-81). Best regards, Roberto Nibali, ratz -- echo '[q]sa[ln0=aln256%Pln256/snlbx]sb3135071790101768542287578439snlbxq' | dc .