Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats is the difference between AutoResetEvent and Mutex

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.

like image 842
D J Avatar asked Jan 11 '12 06:01

D J


People also ask

What is AutoResetEvent?

AutoResetEvent remains signaled until a single waiting thread is released, and then automatically returns to the non-signaled state. If no threads are waiting, the state remains signaled indefinitely. If a thread calls WaitOne while the AutoResetEvent is in the signaled state, the thread does not block.

Is AutoResetEvent a semaphore?

So here is a summary of differences: A Semaphore 's state is manually controlled. A AutoResetEvent 's state is manually set, but automatically reset. With a Semaphore threads typically balance the Release and WaitOne calls.

What is AutoResetEvent and how it is different from ManualResetEvent?

An AutoResetEvent resets when the code passes through event. WaitOne() , but a ManualResetEvent does not.


2 Answers

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 "Release", 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.

like image 123
scegg Avatar answered Oct 18 '22 04:10

scegg


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.

like image 42
Marc Gravell Avatar answered Oct 18 '22 03:10

Marc Gravell