views:

32

answers:

2

I do not understand the use of a mutex if it can be recursively locked by a thread. Why would anyone want to recursively lock the mutex ? In what cases will they use this ?

+2  A: 

I do not understand the use of a mutex if it can be recursively locked by a thread.

A mutex is used to provide mutually exclusive access to a resource. In other words, only one thread (or "agent") should be able to access a resource at a time. Therefore, if a thread has taken a mutex, then it already has exclusive access to the resource, so there is no harm in allowing it to take the mutex again.

A recursive mutex is still useful since it still provides the semantics of exclusive access. While Thread 1 can take a mutex it already has, Thread 2 is still prevented from taking the mutex and accessing the resource at the same time as Thread 1.

Why would anyone want to recursively lock the mutex ?

For convenience: if my thread accesses a resource in a few different classes, each of them can acquire and release the mutex independently and in a nested manner without having to worry about each other. This could be seen as laziness or poor design, but this is an advantage over non-recursive mutexes that cause deadlock when a thread tries to take a mutex it already owns.

Chris Schmich
+1 good answer. It's also interesting that recursive mutexes aren't always possible/supported. Last I checked you can't recursively lock a mutex in the Linux kernel. Not sure about Windows
Sam Post
Good point. For Windows: yes, see http://msdn.microsoft.com/en-us/library/bb202813.aspx
Chris Schmich
@Sam Post: Are you referring to mutexes used within kernel space?
Seamus
@Seamus: yes, I am referring to mutexes inside the kernel. Obviously pthreads and so on implement recursive mutexes, but kernel mutexes that you might use in a driver or filesystem are typically not recursive
Sam Post
A: 

It seems you're asking for a possible use case for a reentrant lock. One would be in the case of using a callback to something. You might have a method which locks an object, and then calls something else, providing a callback with access to this object. If another method is called on this object it might also want to obtain the lock. It's perfectly safe for them both to have the lock, there's no way both can be operating concurrently, they're in the same thread.

Alex Gaynor