[Python-ideas] spinlocks "vs" mutexes

Antoine Pitrou solipsis at pitrou.net
Wed Jul 21 12:26:41 CEST 2010

On Wed, 21 Jul 2010 16:22:27 +1000
Cameron Simpson <cs at zip.com.au> wrote:

> On 21Jul2010 02:51, Sturla Molden <sturla-PujZ2ClILZlhl2p70BpVqQ at public.gmane.org> wrote:
> | Thread synchronization with threading.Lock can be expensive. But
> | consider this: Why should the active thread need to aquire a mutex,
> | when it already holds one? That would be the GIL.
> | 
> | Instead of acqiring a lock (and possibly inducing thread swiching
> | etc.), it could just deny the other threads access to the GIL for a
> | while. The cost of that synchronization method would be completely
> | amortized, as check intervals happen anyway.
> [...]
> | The usecase for this "gillock" is about the same as for a spinlock
> | C. We want synchronization for a breif period of time, but don't
> | want the overhead of aquiring a mutex.
> But a spinlock _does_ acquire a mutex, unless I misremember.
> It is just that instead of using a more expensive mutex mechanism that
> deschedules the caller until available it sits there banging its head
> against a very lightweight (not descheduling) mutex until it gets it;
> the efficiency is entirely reliant on _all_ users of the spinlock doing
> very little inside the located period.

Not only that, but optimized OSes and libc's might do the same as
an optimization for regular mutexes.
For example, here's what the pthreads(7) man page says here:

“thread synchronization primitives (mutexes, thread joining, etc.) are
implemented using the Linux futex(2) system call.”

I don't know exactly how futex(2) works, but it looks like a kind of
low-level API allowing to build spinlocks and other fast userspace



More information about the Python-ideas mailing list