Subj : Re: recursive mutexes To : comp.programming.threads From : Uenal Mutlu Date : Thu May 19 2005 02:49 pm "David Schwartz" wrote > > "Uenal Mutlu" wrote in message > > >> 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. True, but it still works. If the prev. lock owner is that fast to request immediately a new lock on the same (now unlocked by him) object, and if the next candidate still is in sleep then it will be again the old owner who gets the lock again. This rare case can be eliminated by spinning, but I've found sleeping some random ticks is better. So, yes, your brilliant observation is again true. But it is IMO a neglectable and harmless case, because who does unlock and immediately try to lock again the same mutex? BTW, in case you haven't figured it out already (which I doubt), there must be a decrement before it returns false in trylock... > 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. One could also use an ordinary right aligned variable in TLS but then there are more operations to do... Just try it out and let's know about the result. .