gpt4 book ai didi

c# - Monitor.PulseAll() 中需要帮助

转载 作者:行者123 更新时间:2023-11-30 13:52:43 24 4
gpt4 key购买 nike

任何人都可以用简单的例子来解释我如何处理 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(又名 lock)时,有两种类型的阻塞;有一个“就绪队列”,线程在其中排队等待执行。在 Console.WriteLine("Pool thread wants the lock"); 之后的行中,池队列进入就绪队列。当锁被释放时,就绪队列中的线程可以获得锁。

第二个队列用于需要唤醒的线程;对 Wait 的调用将线程置于第二个队列中(并临时释放锁)。对 PulseAll 的调用将所有线程从第二个队列移动到就绪队列(Pulse 只移动一个线程),因此当池线程释放锁时,主线程是允许再次拿起锁。

这听起来很复杂(也许确实如此)- 但它并没有听起来那么糟糕……老实说。然而,线程代码总是很棘手,需要谨慎和清醒地处理。

关于c# - Monitor.PulseAll() 中需要帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1561406/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com