tech-userlevel archive

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index][Old Index]

Re: Contended locks - mutex vs spin lock

On 30.10.2011 12:30, Sad Clouds wrote:
Hi, I was expecting for a contended lock, spin lock to be at
least as efficient as adaptive mutex. However a simple test program
seems to indicate quite a big difference:

atom$ gcc -O2 lock_test.c -DMUTEX_LOCK -lpthread
atom$ time ./a.out
         4.54 real        16.76 user         0.00 sys

atom$ gcc -O2 lock_test.c -DSPIN_LOCK -lpthread
atom$ time ./a.out
        14.04 real        51.83 user         0.00 sys

Any idea why pthreads spin lock is 3 times slower compared to pthreads

At first glance I'd say that it largely depends on the micro-benchmark you are using, especially /how/ you are hammering on the contended lock.

Sometimes it may be easier for a program to make progress with mutexes because sleeping threads can let other threads run uncontended for a long time; if a thread is performing pthread_mutex_lock/unlock in a tight loop, I bet the loop will be faster as the lock/unlock will take the fast path most of the time.

Whereas spin locks could generate live locking situations where progress happens, albeit slower. Like a 4x100 metres relay but with a lot more changeovers.

Jean-Yves Migeon

Home | Main Index | Thread Index | Old Index