94a Subj : Re: recursive mutexes To : comp.programming.threads From : Uenal Mutlu Date : Mon May 16 2005 12:01 pm "doug" wrote > > > You seem to not understand what I'm talking about. > > Do you understand this fact: "Recursive locking is defined for the current > > lock owning thread only"? > > Since you already have the lock you can do what ever you want since nobody > > else can change anything, but you can do! You simply increment it in > > Lock() > > and decrement it in Unlock(). Because it is safe because you already have > > it locked. > > > Think carefully. How is this possible? It is really basic stuff. Ask yourself how you would extend a non-recursive locking method to make it recursive? Recursivity starts with the 2nd Lock() call on the same object within the same thread, true? So, after the 1st you already have the lock, don't you? From then on just use a simple unprotected counter. It is intended for the current _lock owning thread_ only. It is irrelevant for all other threads because they don't have the lock. Let me know if this makes sense to you. > It is possible if you store 'have I got this lock?' in thread local storage. > So yes, by keeping a counter here, you don't need a memory barrier in > recursive Lock()/Unlock() *. However, when you find that you don't have the > semaphore, you still need synchronisation between threads so that the sema4 > is acquired safely. > What you've ended up doing here is accessing TLS for *every* acquire - thus > making the common case of 'semaphore not acquired' slower. > > (* not true on certain SMP architectures. Without a memory barrier in > Lock()/Unlock(), a thread rescheduled on a different CPU may mis-read the > recursive counter (depending on how TLS is implemented).) I think I now know what the reason of these misunderstandings are: You and some others seem to see a lock as a property of a thread, and by this you do "lock the thread". I on the other hand see a lock as a property of the shared object. I don't use any TLS, I use just the usual sharing mechanism of threads; ie. all objects in a program can be accessed by all threads. By this, I put locks on objects, not threads. Each such shared object has its own mutex, and not one mutex per thread, and of course also not one mutex for all threads (which IMO is nonsense). . 0