From: "Ted Unangst" Subject: Re: rpki-client: pthreads first unlock then signal To: "Job Snijders" Cc: "Mark Kettenis" , tech@openbsd.org Date: Tue, 24 Jun 2025 00:46:16 -0400 On 2025-06-23, Job Snijders wrote: > On Tue, Jun 24, 2025 at 12:25:06AM +0200, Mark Kettenis wrote: > > > Date: Mon, 23 Jun 2025 22:13:51 +0000 > > > From: Job Snijders > > > > > > While this is not fixing a bug, intuition and literature suggest that > > > unlocking mutexes before signaling might help prevent the > > > freshly-woken-up thread from humping against the lock. > > > > Where did you find this questionable advice? > > I quote from The Linux Programming Interface, chapter 30.2 "Signaling > Changes of State: Condition Variables" (page 647) > > """ [Butenhof, 1996] points out that, on some implemenations, > unlocking the mutex and then signaling the condition variable > may yield better performance than performing these steps in the > reverse sequence. If the mutex is unlocked only after the > condition variable is signaled, the thread performing > pthread_cond_wait() may wake up while the mutex is still locked. > This results in two superfluous context switches. Some > implementations eliminate this problem by employing a technique > called "wait morphing", which moves the signaled thread from the > condition variable wait queue to the mutex wait queue without > performing a context switch if the mutex is locked.""" > > Is there a reason to signal and then unlock? If that is the case, > shouldn't the calls around line 1268 parser.c:proc_parser() be be > reversed? I think it's clearer to keep the mutex held around the signal, lest somebody start changing things and then the mutex disappears entirely. You need the mutex at least to decide when to signal. It's correct either way. Incidentally, we have the code for the optimization, but not enabled.