One ManualResetEvent, multiple threads waiting

E

Elhurzen

X-No-Archive: Yes
From what I understand, if multiple threads are waiting on a
ManualResetEvent after calling WaitOne(), only one thread is guaranteed
to be signaled when Set() is called on that ManualResetEvent. How do I
ensure that _all_ waiting threads are signaled, without sacrificing any
of the functionality or much of the simplicity of ManualResetEvent?

Example:

SignalingClass:
ManualResetEvent handle = new ManualResetEvent(false);

void SomeRandomMethod() { handle.Set(); }

Thread #1: SignalingClassObject.handle.WaitOne();
Thread #2: SignalingClassObject.handle.WaitOne();
 
W

William Stacey [MVP]

It is my understanding that all current waiting threads are moved to the
ready queue, so they will run when the OS schedules them. Any other threads
will go right to ready queue until the event is reset(). Are you not seeing
this behavior?
 
E

Elhurzen

I've noticed an error in my original question after checking with MSDN
docs.

MSDN on ManualResetEvent:
"Threads that call WaitOne on the ManualResetEvent will block, awaiting
the signal. When the controlling thread completes the activity, it
calls Set to signal that the waiting threads can proceed. *** All
waiting threads are released. ***"

But for AutoResetEvent, MSDN says:
"Calling Set signals AutoResetEvent to release a waiting thread.
AutoResetEvent remains signaled *** until a single waiting thread is
released ***, and then automatically returns to the nonsignaled state.
If no threads are waiting, the state remains signaled indefinitely."

I read the AutoResetEvent description and assumed that the same would
apply to ManualResetEvent.

But ManualResetEvent wakes up ALL waiting threads while AutoResetEvent
might move on after waking up just one. I haven't actually been able to
try this, but please correct me if I've understood this incorrectly.

Why is there such a discrepancy? Why can't AutoResetEvent wake up all
of its own waiting threads?

In any case, my "problem" with ManualResetEvent seems to be solved. :)
 
W

William Stacey [MVP]

That is correct. That is why they have two. ARE releases one thread and
resets automatically and MRE releases all of them and you "manually" decide
when to reset. The one you pick depends on what your doing in the
application.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top