cvs commit: src/sys/vm vm_zeroidle.c

John Baldwin jhb at
Sun Jul 3 01:16:52 GMT 2005

On Monday 08 November 2004 07:49 pm, Don Lewis wrote:
> On  8 Nov, John Baldwin wrote:
> > It is no longer required to hold the mutex over cv_wait() and
> > cv_signal().  I intentionally changed that so that you can do:
> >
> > 	lock()
> > 	blah()
> > 	unlock()
> > 	cv_signal()
> >
> > and reduce the number of context switches if you preempt in cv_signal().
> cv_wait() unlocks and relocks the mutex, so it is necessary to hold the
> mutex before calling cv_wait().  It is also likely that the mutex would
> have to be held to avoid having the condition being waited on going away
> after the mutex was dropped and before the cv_wait() call, which could
> cause the thread to miss a wakeup and sleep forever.

Ok, this is fairly standard practice and nothing new here.  Even spl() on 4.x 
required you to keep the spl raised when you called tsleep() which is 
similar.  (That is when sleeping you should generally do:

	while (still_need_to_sleep())

> If the caller holds the mutex across the call to cv_signal(), the caller
> may be able to avoid calls to cv_signal() if it knows that there are no
> waiters.  In most cases, the caller will want to release the mutex when
> it calls cv_signal().  A version of cv_signal() that releases the mutex
> after calling sleepq_lock() and before calling sleepq_signal() or
> sleepq_release() would allow unnecessary calls to sleepq_signal() to be
> optimized out, while avoiding the extra context switches that could be
> caused by holding the mutex until after cv_signal().

You can already do this by just dropping the lock before cv_signal() now, 

	if (wakeup_needed)
		need_wakeup = 1;
		need_wakeup = 0;
	if (need_wakeup)

cv_signal() itself has some optimizations so that for most cases when there 
are no waiters it won't bother do a sleepq_signal() but instead will just 
lock the spin mutex, check the waiters count, and then bail.

John Baldwin <jhb at>  <><
"Power Users Use the Power to Serve"  =

More information about the cvs-src mailing list