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

标签 c# multithreading

任何人都可以用简单的例子来解释我如何处理 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/

相关文章:

C# 帮助需要更改删除长路径文件夹的代码

multithreading - ViewModel 和多线程最佳实践

c++ - 对自己的互斥锁类使用lock_guard

java - newKieSession 是线程安全的吗?

c# - ESQL 不工作

c# - 如何将字典参数传递给 web-api 方法?

c# - 如何将类实例转换为 JsonDocument?

c# - 如何在Azure表存储中使用RowKey或时间戳检索最新记录

objective-c - Objective-C 的 NSMutableArray 是线程安全的吗?

c++ - CppUnit的多线程实现?