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

1.1k views Asked by At

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.

2

There are 2 answers

1
Giorgi Chkhikvadze On BEST ANSWER

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.

0
Ben Voigt On

The .NET System.Threading.Mutex class uses a Win32 kernel mutex object which is re-entrant. The following note from the documentation explains correct usage:

The thread that owns a mutex can request the same mutex in repeated calls to WaitOne without blocking its execution. However, the thread must call the ReleaseMutex method the same number of times to release ownership of the mutex.

Clearly then, the OS is counting the number of times the mutex is entered -- it is NOT a binary state of "locked or unlocked" (beside the count, there's an additional state of "abandoned").