Re: How Mutexes Work
Re: How Mutexes Work
- Subject: Re: How Mutexes Work
- From: Greg Parker <email@hidden>
- Date: Thu, 12 Feb 2009 23:08:27 -0800
On Feb 12, 2009, at 6:34 PM, Dave Keck wrote:
Today, for some reason or another, I've been pondering how locks work.
After locating the pthread source (in libc, available at
opensource.apple.com, for those curious) I've found the source for the
pthread_mutex_lock, in pthread_mutex.c It seems the meat of this
function are the macros 'LOCK' and 'PLOCKSTAT_MUTEX_ACQUIRE'.
The 'LOCK' macro is defined (indirectly) as _spin_lock. _spin_lock is
implemented in various places based on the architecture you're
compiling for; in my case I'm interested in i386. For that, _spin_lock
is defined as:
_OSSpinLockLock:
_spin_lock:
__spin_lock:
movl $(_COMM_PAGE_SPINLOCK_LOCK), êx
jmpl *êx
.align 2, 0x90
.globl _OSSpinLockUnlock
.globl _spin_unlock
.globl __spin_unlock
But I can't seem to find what _COMM_PAGE_SPINLOCK_LOCK is. I'm taking
a shot in the dark that it's a function address in the kernel's
address space. Is this correct? (I'm no assembly expert! :)) If so,
where is the value for _COMM_PAGE_SPINLOCK_LOCK set?
The "comm page" is an area of memory in user space which is shared
across all processes and whose contents are controlled by the kernel.
It's used for various low-level bits of code like memcpy and spinlock
that are tuned carefully for machine-specific details such as CPU type
and processor count.
Code for at least some of the comm page's functions is in xnu/osfmk/
<arch>/commpage/ . spinlock for i386 is xnu/osfmk/i386/commpage/
spinlocks.s, where there are versions optimized for single- and multi-
processor machines, both 32- and 64-bit.
Secondly we have PLOCKSTAT_MUTEX_ACQUIRE. I can't seem to find where
it's defined either, and it seems to be the real heavy-lifter for
pthread_mutex_lock. Any ideas?
Ignore anything plockstat-related. That's just a hook for lock
statistics via dtrace, and I don't even know if it's enabled by
default. pthread_mutex is based on spinlocks plus either Mach
semaphores or kernel mutexes, depending on the pthread mutex
attributes requested.
Lastly and perhaps most important, is there a good low-level OS book
that might explain the nitty gritty when it comes to locks and
everything else deep under-the-hood?
Amit Singh's Mac OS X Internals (http://osxbook.com) contains more
nitty gritty than you can shake a stick at, but I don't know what his
pthreads discussion looks like. Any OS textbook should be a good
source for the general ideas of how to write synchronization
primitives like spinlock or compare-and-swap and then build higher-
level constructs with them.
--
Greg Parker email@hidden Runtime Wrangler
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Darwin-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden