Monitor.Pulse和Monitor.PulseAll的区别 [英] Difference between Monitor.Pulse and Monitor.PulseAll
问题描述
Monitor.PulseAll
通知所有等待的线程在队列中。
Monitor.Pulse
通知线程排队等候。 (下等待线程)
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?
当我应该用脉冲
VS PulseAll
?
推荐答案
使用 PulseAll
当你想唤醒多个线程,因为条件,他们正在等待5月现在必须满足对一个以上的线程。 (等待是几乎总是与一个条件相关的 - 你通常应该测试在,而
循环条件)
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.
要举两个类比:
想象一下,你有一台打印机。只有一个人可以一次使用它,所以如果你有很多人在等,你它们发送到睡眠 - 但你只唤醒一个人了,当打印机空闲。这反映了使用脉冲
。
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
.
现在想象你运行一个商店。当你关闭,顾客等候在店外。当你开的店,你不只是要唤醒一个客户 - 他们可以现在都进来了。这反映了使用 PulseAll
。
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
.
这篇关于Monitor.Pulse和Monitor.PulseAll的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!