[Development] QMutex with pthread on Linux

Olivier Goffart olivier at woboq.com
Sun Aug 26 10:45:31 CEST 2012


On Tuesday 21 August 2012 22:36:38 Thiago Macieira wrote:
> Hello
> 
> I've just done some benchmarking of QMutex on Linux, using the pthread
> implementation instead of the futex one.
> 
> Conclusions first:
> 
> QMutex is optimised for uncontended case. It does that by keeping the d
> pointer at NULL while unlocked, and uses 0x3 to indicate it's locked.
> Changing from one value to another is extremely quick, requiring a simple
> atomic operation. QMutex when uncontended proves to be roughly 16% faster
> than pthread. This also shows in the benchmarks that use non-zero msleep:
> the mutex is mostly uncontended.
> 
> That comes at a price, though: the performance drops considerably when
> contention happens.
> 
> When contention happens at a low rate (the "msleep(0)" case), QMutex
> performance is similar to that of pthread, though slightly worse (up to 5%).
> 
> When contention happens a lot, the performance is awful. I've measured
> anything from 100% slower to over 1000%.
> 
> Extrapolating these results to Mac and Windows, I expect QMutex performance
> in uncontended to be *much* better, but still lose horribly in the
> contended case.
> 
> Conclusion: I'm glad I use Linux and that we have futex.

Keep in mind that the micro benchmark really stress the mutexes, and is not 
really realistic: The benchmark do nothing outside the lock.
In a typical scenario, if you use multiple thread, it is because you want to 
paralellize something.  
In that benchmark, a lot of pressure is put on the freelist and the loop 
inside lockInternal. But in a normal case, in which the number of operation 
outside of the lock is significant, there shoud be much less pressure on this 
loop, and the testAndSet fails much less often.

Also, maybe one could also optimize the pthread code we use by using semaphore 
instead. Or maybe just mutexes and no waitcondition. The problem is that 
pthread mutex can't do timed lock, so we need to be smart in order to allow 
tryLock(timeout).  (We could try to do it with a wait condition only if we 
detect the mutex has been used with a timeout)


-- 
Olivier

Woboq - Qt services and support - http://woboq.com




More information about the Development mailing list