Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Monitor.Pulse and Monitor.PulseAll

Monitor.PulseAll notifies all waiting threads in the queue.

Monitor.Pulse notifies a thread in the waiting queue. (The next waiting thread)

Only the next thread (one thread) can acquire the lock. So what is the difference?

When should I use Pulse vs PulseAll?

like image 699
Michael Piendl Avatar asked Mar 23 '09 21:03

Michael Piendl


People also ask

What does the C# method monitor PulseAll () do?

Enter method does not protect variable x at all. What does the C# method Monitor. PulseAll() do? Move all threads in waiting state into ready state.


1 Answers

Use PulseAll when you want to wake up multiple threads, because the condition they're waiting for may now be fulfilled for more than one thread. (Waiting is almost always associated with a condition - you should usually be testing that condition in a while loop.)

Use Pulse when you only want to wake up one thread, because only one thread will actually be able to do useful work.

To give two analogies:

Imagine you've got a single printer. Only one person can use it at a time, so if you're got a lot of people waiting, you send them all to sleep - but you only wake one person up when the printer becomes free. This mirrors the use of Pulse.

Now imagine you run a shop. While you're closed, customers wait outside the shop. When you open the shop, you don't just want to wake up one customer - they can all come in now. This mirrors the use of PulseAll.

like image 171
Jon Skeet Avatar answered Sep 25 '22 20:09

Jon Skeet