multithreadingthread-safetymutexrecursive-mutex

How does the recursive(reentrant) mutex works?


I read two articles at http://preshing.com/20120305/implementing-a-recursive-mutex as well as http://en.wikipedia.org/wiki/Reentrant_mutex on recursive(reentrant) mutex, but neither article made any sense.

Could someone explain how recursive(reentrant) mutex works ?

(I found very little material explaining how recursive mutex works. If anyone has link with good explanation, I would will close this question.)

Thanks !


Solution

  • One simple way to do this is to pair a standard mutex with the following auxiliary information:

    You can then acquire the mutex in the following way:

    In other words, if you own the mutex already, you just increment a counter indicating that you now own it even more. If not, you acquire the mutex as usual.

    You can then release the mutex in the following way:

    In order for this to work, you need to be able to read the counter and mutex owner in a thread-safe way. You can do this either by having a secondary mutex to guard it, or by marking the counter / owner volatile.

    Hope this helps!