Subj : Re: recursive mutexes To : comp.programming.threads From : David Schwartz Date : Wed May 18 2005 02:04 pm "Uenal Mutlu" <520001085531-0001@t-online.de> wrote in message news:d6g5na$an4$01$1@news.t-online.com... >> It's so horribly broken that, if anything, it proves my point. For >> example, the 'TryLock' function increments the lock count even if some >> other >> thread holds the lock. It's hard to imagine how you can write a sane >> 'Unlock' function once you've made it impossible to tell whether the lock >> actually gets unlocked or not. > It is not broken, and your observation is correct. Just think of a > decrement somewhere > and you'll have found the holy grail... :-) That won't help you. The thread that does the increment holds no locks of any kind at the time it does the increment (assuming it's this thread's first try at the lock), so there's no way to make the thread doing the unlock wait until after the decrement. Remember, the code was: > void Lock(someparam) > { > if (TryLock(someparam)) and > bool TryLock(someparam) > { > if (++cLocked == 1) // actually an atomic pre-increment operator (ie. > class method) So the thread atomically increments 'cLocked' even if another thread holds the lock and without holding any locks itself. Suppose the thread just finishes the '++cLocked' and then gets pre-empted for a long time. What happens when the thread that holds the lock decrements 'cLocked' and it doesn't go to zero? It will think it still holds the lock. There could possibly be ways to get yourself out of this mess in the "magic and undisclosed" parts. But it would be a horribly ugly and frightening implementation. It certainly would bear no resemblance to recursive mutexes as they're actually implemented. In any event, a single atomic increment costs about 200 cycles on a P4. DS .