Subj : Re: recursive mutexes To : comp.programming.threads From : Casper H.S. Dik Date : Thu May 19 2005 09:49 am "Uenal Mutlu" <520001085531-0001@t-online.de> writes: >"Casper H.S. Dik" wrote >> "Uenal Mutlu" writes: >... >> (The recursive mutex is only slightly more expensive >> than the ordinary mutex as the unlock path is more >> expensive) >Actually it is just an increment and a comparision of the currentthreadid vs. >the lock holding threadid in Lock(), and a simple decrement in Unlock(). >The overhead for recursively locking is far less than the first aquisition >(== non-recursive mutex) of the lock. Cf. code snippet of my other posting to doug and David. You will always need to attempt to acquire the lock first; if not, there's nothing you can say about the state of the lock. Recursively acquiring the lock is actually not less expensive because of that. You cannot increment the lock count until you know that you are the current lock owner. In pseudo code, the Solaris recursive mutex is something like this: Lock: if (TestAndSetLockByte(&lock)) { /* Fast path, we managed to own the lock */ lock.owner = MyThreadId(); return; } /* Verify the owner */ if (lock.owner == MyThreadId()) { lock.count++; return; } /* Slow path, go to sleep until it's unlocked */ Unlock: if (lock.count == 0) { ReleaseLock(&lock); return; } lock.count--; return; In fact, it's the verification of the thread id and the lock increment which makes this more expensive than the ordinary lock, similarly for the unlock operation which requires you to check the lock count; the extra load and test are measurable. The lock count is not incremented when the lock is first acquired; so the count is always 1 lower than the actual number of holds. Casper -- Expressed in this posting are my opinions. They are in no way related to opinions held by my employer, Sun Microsystems. Statements on Sun products included here are not gospel and may be fiction rather than truth. .