Search code examples
cwindowsposixmutex

How to alter the recursive locking behaviour of Windows Mutex?


Windows Mutex seems to allow an acquired lock to be acquired again (recursively) if the thread currently owning the lock tries to acquire it.

But, posix based pthread locks don't allow such a behaviour.

Is there any compile time macro or any settings which can make the windows mutex behave in the same way as the pthread mutex?


Solution

  • As long as you program in Windows, avoid reimplementing the behavior of its Mutex. It being re-entrant by the same thread is absolutely essential for its defined behavior.

    A sync object without thread affinity is a semaphore that counts to 1. Use CreateSemaphore().

    Fwiw, it is very curious that you need this kind of behavior. It sounds like you are trying to use the same sync object in multiple places inappropriately. You can use the semaphore but you'll lose concurrency potential. Consider using more than one mutex instead.