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!