Subj : Re: Futexes are wrong! (Are they?) To : comp.programming.threads From : Maciej Sobczak Date : Tue Jun 07 2005 10:09 am David Schwartz wrote: > Generally, you get better performance if you signal after the mutex is > freed. Is there a short way to explain the reason for this difference? What about wait morph that can be performed for threads waiting on the condvar while the mutex is still locked by the signalling thread? > This should be used except in the very rare cases where it creates a > problem. FWIW, in my many years of multi-threaded programming, I have never > encountered such a case and have only come close to deliberately > constructing one. I'm aware of a compelling design-wise explanation why signalling before releasing the mutex is good - this is because you signal something that you know is true at the time of signalling. I agree that doing otherwise (signalling after freeing the mutex) should not pose any problems in popular usage patterns, but the "purity" argument sounds good to me. In general, the difference can be explained in the following terms: 1. When I signal before unlocking the mutex, I signal the state that I know is true (because I own the mutex): "Hello, I did it and I know that it's done". This may force the unnecessary context switch: waiting thread leaves the condvar just to fall asleep on the mutex that it cannot lock. But there is wait morph (or is there?). 2. When I signal after unlocking the mutex, I don't really know what I signal, because the state of interest can be no longer true (because I don't own the mutex and somebody else could have intercepted me): "Hello, I did it, but I have no idea what happened from that time, so what I'm telling you may be already false". This may force the waiting thread(s) to wake up just to find out that the condition is not true and fall back to wait on the condvar again. I'm not really sure whether any of these two scenarios is inherently ("generally") faster than the other, but the first scenarion sounds better to me in terms of design logic. That's what I usually do. I might as well mix things up completely, so any explanation is welcome. -- Maciej Sobczak : http://www.msobczak.com/ Programming : http://www.msobczak.com/prog/ .