Question

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 !

Était-ce utile?

La solution

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

  • A pointer to the thread that owns the mutex (or NULL if it's not acquired), and
  • A counter, which is initially 0.

You can then acquire the mutex in the following way:

  • If you are the current mutex owner, increment the counter and return immediately.
  • If not, acquire the mutex and set the counter to 0.

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:

  • If the counter is nonzero, decrement the counter and return immediately.
  • Otherwise, release the mutex.

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!

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top