任何人都可以用简单的例子来解释我如何处理 Monitor.PulseAll()。我已经从这个 stackoverflow 中获取了一些示例。由于我是初学者,我觉得这些超出了我的理解范围。
怎么样(展示互动):
static void Main()
{
object obj = new object();
Console.WriteLine("Main thread wants the lock");
lock (obj)
{
Console.WriteLine("Main thread has the lock...");
ThreadPool.QueueUserWorkItem(ThreadMethod, obj);
Thread.Sleep(1000);
Console.WriteLine("Main thread about to wait...");
Monitor.Wait(obj); // this releases and re-acquires the lock
Console.WriteLine("Main thread woke up");
}
Console.WriteLine("Main thread has released the lock");
}
static void ThreadMethod(object obj)
{
Console.WriteLine("Pool thread wants the lock");
lock (obj)
{
Console.WriteLine("Pool thread has the lock");
Console.WriteLine("(press return)");
Console.ReadLine();
Monitor.PulseAll(obj); // this signals, but doesn't release the lock
Console.WriteLine("Pool thread has pulsed");
}
Console.WriteLine("Pool thread has released the lock");
}
重新发信号;当处理Monitor
(aka lock
),阻塞有两种类型;有一个“就绪队列”,线程在其中排队等待执行。之后上线Console.WriteLine("Pool thread wants the lock");
池队列进入就绪队列。当锁被释放时,就绪队列中的线程可以获取锁。
第二个队列用于需要唤醒的线程;打电话给Wait
将线程放入第二个队列中(并暂时释放锁)。致电给PulseAll
将所有线程从第二个队列移动到就绪队列(Pulse
只移动一个线程),这样当池线程释放锁时,主线程就可以再次获取锁。
这听起来很复杂(也许确实如此)——但老实说,它并不像听起来那么糟糕。然而,线程代码是always棘手,需要谨慎和清醒的头脑来对待。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)