Whats is the difference between AutoResetEvent and Mutex

7.4k views Asked by At

I am new to these concepts. But as i am going deeper in threading i am getting confused.

What is the significance of mutex, semaphore over autoresetevent.

Only difference i came to know with studies is that a mutex can perform across process operations. If this is the case why it does not have same method as Set, Reset, WaitOne.

Can we replace the AutoResetEvent with mutex and vice versa?

Please solve this puzzle.

3

There are 3 answers

4
Marc Gravell On BEST ANSWER

Different concept - a Mutex is an exclusive token; only one person can have it; when they release it, somebody else can fight over it. An AutoResetEvent is a gate that allows exactly one person through before closing, and which is operated by a button that is separate to the queue of people wanting to go through. When they pass through the gate immediately closes.

0
Vishwas S L On

Mutex is blocking the threads to access the Critical section; Here In AutoResetEvent, I see the focus is not on blocking the critical section rather on the Signal it should receive from any other thread. Once it is signalled, it is allowed to continue the execution.

AutoResetEvent also provide an option to handle race condition, lets say set() event is called first then some thread calls wait() on it then wait() immediately receives the signal given by set() and anyway vice versa also works fine.

Also If multiple set() are called before any wait() on it and then wait() arrives multiple set() will continue to be valid, Only one set() can be waiting for wait() and remaining would vanish immediately.

0
scegg On

It depends.

In common, AutoResetEvent and Mutex can be replaced, AutoResetEvent.WaitOne = Mutex.WaitOne and AutoResetEvent.Set = Mutex.ReleaseMutex.

But they are different. You may mentioned that the Mutex has a "ReleaseMutex", which means you may "get" something while calling "WaitOne". The thing you may get is related to the thread which is calling.

You can call AutoResetEvent.Set in any thread. But you can only call Mutex.ReleaseMutex from the thread which is called Mutex.WaitOne and get the true as result.