1

我遇到了一个问题,我将其简化为这个最小的测试用例,但我仍然不明白为什么它不能正常工作。这里的代码很简单:父线程获取一个锁,然后启动一个子线程,然后通过在其上启动 await 来释放锁。然后被锁定在同一个锁上的子线程继续执行,释放父线程,然后休眠五秒钟。

using System.Threading;
using System;
using System.IO;
using System.Diagnostics;

namespace Test
{
    class MainClass
    {
        public static void Main(string[] args)
        {
            Object waitForThrToStart = new Object();
            lock (waitForThrToStart)
            {
                new Thread(() =>
                {
                    lock (waitForThrToStart)
                    {
                        Debug.WriteLine("2. Child: free the parent");
                        Monitor.Pulse(waitForThrToStart);
                        Debug.WriteLine("3. Child: pulsed ☺ Now sleep");
                        Thread.Sleep(5000);
                        Debug.WriteLine("5. Child: time out");
                    }
                }).Start();
                Debug.WriteLine("1. Parent: waiting");
                Monitor.Wait(waitForThrToStart);
                Debug.WriteLine("4. Parent: awoke, exiting now");
            }
        }
    }
}

没关系,除了……它不起作用。父级仅在五秒钟后释放,当子级退出时,您可能会在输出中看到它:

1. Parent: waiting
2. Child: free the parent
3. Child: pulsed ☺ Now sleep
5. Child: time out
4. Parent: awoke, exiting now

我什至尝试过使用Monitor.PulseAll(),但这并没有改变任何东西。我还想,也许出于某种奇怪的原因,孩子得到了 Object 的副本,因此他们在处理不同的变量。但是我通过在父母中设置一个电话来反驳它Sleep()- 孩子肯定在等待锁定。

这是什么,是bug吗?有什么解决方法吗?

4

1 回答 1

3

您正在以孩子的身份对监视器进行脉冲,但您也已将其锁定。只有在您释放子线程中的Wait锁后才会返回,此时它需要在返回之前重新获取锁。

于 2015-03-19T11:09:42.627 回答