"Lockless" sounds very positive, and it's tempting to think that everything should be made lockless. However, it's less great than it sounds. Mutexes are very cheap in the uncontended case, and in the contended case they have some nice properties. You should only consider going for a lockless algorithm if you can prove it is better than just using a mutex. Sometimes lockless algorithms are in fact slower than algorit…
> You should only consider going for a lockless algorithm if you can prove it is better than just using a mutex. I would, in fact, give precisely the reverse advice for one reason: Mutexs don't compose. Mutexs are really good at putting subtle bugs into your code that are ridiculously difficult to figure out. Lockless algorithms may be slower or cause performance issues, but they don't malfunction because you got the…
The don't compose because (as you hinted) lock taking/releasing order has to be the same for all callers, but if mutexes are being taken behind the scenes then API usage order becomes critical, and it is trivial to screw that up.
> Lockless algorithms may be slower or cause performance issues, but they don't malfunction because you got the release order backwards.
And they may scale better. Scalability is important.
For me the classic case is rw locks vs. RCU-ish schemes. I think there's no case where rw locks are ever appropriate if you have an RCU-ish alternative. For example, OpenSSL uses only rw locks -- nuts!