Subj : Re: recursive mutexes To : comp.programming.threads,comp.unix.programmer From : =?iso-8859-1?q?M=E5ns_Rullg=E5rd?= Date : Sun May 15 2005 01:41 pm "Uenal Mutlu" <520001085531-0001@t-online.de> writes: > "David Schwartz" wrote >> red floyd wrote: >> >> > May I ask why? >> >> There are two possibilities: >> >> 1) You don't know the mutex is being used recursively. In this case, the >> recursive mutex will hide a serious problem. >> >> 2) You know the mutex is being recursively. In this case, just don't >> lock it since you know it's already locked anyway. >> >> The problem is that recursive mutexes hide something from you and that >> something is extremely important. Consider code like this: >> >> A) Lock mutex >> B) Unlock mutex >> C) Do something, assuming the mutex is unlocked >> >> What happens if the mutex is recursive? > > Recursive locks work only for the same (current) thread. I sure hope so. > The code above is IMO wrong, obviously it should be: > A) Lock mutex > B) Do something > C) Unlock mutex David meant what he said. What if the something is signaling another thread to go ahead with something that locks the mutex, and then wait for that other thread to signal you back? Deadlock. > and this is ok too (here the recursive feature is in action): > A) Lock mutex > B) Do something > C) Lock mutex > D) Do something2 > E) Unlock mutex > F) Unlock mutex > > C and E are redundant, however application code (the current thread) > cannot always know that it alread has the lock, though it could test > for it. Bad application design. A properly designed application will always know what to expect. >> It's just too hard and dangerous to write sensible code that >> works with a mutex that might or might not start out with that >> mutex locked and with no way to tell which. And the only value of >> recursive mutexes is that they let you do this. > > Lock objects are initialized at creation, they don't have a random > state. Recursive locks are very practical. It saves coding and > prevents from self-deadlocking. In all the years I've been programming, I have never used a recursive mutex (except in Java, but that's another story). -- Måns Rullgård mru@inprovide.com .