Search code examples
c#mutexrecursive-mutex

Can a thread call .WaitOne() of a Mutex more than once before calling .ReleaseMutex() and vice versa?


In my code, it would be convenient if my thread calls .WaitOne() more than once before calling .ReleaseMutex().

And vice versa: Calling .ReleaseMutex() a few times before restarting a loop which begins with call to .WaitOne().

Some operating systems / compiler combinations allow this. Some don't.


Solution

  • Mutex has 2 state only: locked or unlocked. It can't be locked twice or unlocked twice. Something that you want is Semaphore: See Here. Semaphore has counter and after each WaitOne counter decreases by 1, and after each call of Release counter increases by 1.