【发布时间】:2013-02-10 14:53:10
【问题描述】:
ManualResetEventSlim:调用 .Set() 后立即调用 .Reset() 不会释放任何等待线程
(注意:ManualResetEvent 也会发生这种情况,而不仅仅是 ManualResetEventSlim。)
我在发布和调试模式下都尝试了下面的代码。 我在四核处理器上运行的 Windows 7 64 位上使用 .Net 4 将其作为 32 位版本运行。 我从 Visual Studio 2012 编译它(所以安装了 .Net 4.5)。
当我在我的系统上运行它时的输出是:
Waiting for 20 threads to start
Thread 1 started.
Thread 2 started.
Thread 3 started.
Thread 4 started.
Thread 0 started.
Thread 7 started.
Thread 6 started.
Thread 5 started.
Thread 8 started.
Thread 9 started.
Thread 10 started.
Thread 11 started.
Thread 12 started.
Thread 13 started.
Thread 14 started.
Thread 15 started.
Thread 16 started.
Thread 17 started.
Thread 18 started.
Thread 19 started.
Threads all started. Setting signal now.
0/20 threads received the signal.
所以设置然后立即重置事件并没有释放单个线程。如果取消对 Thread.Sleep() 的注释,那么它们都会被释放。
这似乎有些出乎意料。
有人解释一下吗?
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Demo
{
public static class Program
{
private static void Main(string[] args)
{
_startCounter = new CountdownEvent(NUM_THREADS); // Used to count #started threads.
for (int i = 0; i < NUM_THREADS; ++i)
{
int id = i;
Task.Factory.StartNew(() => test(id));
}
Console.WriteLine("Waiting for " + NUM_THREADS + " threads to start");
_startCounter.Wait(); // Wait for all the threads to have called _startCounter.Signal()
Thread.Sleep(100); // Just a little extra delay. Not really needed.
Console.WriteLine("Threads all started. Setting signal now.");
_signal.Set();
// Thread.Sleep(50); // With no sleep at all, NO threads receive the signal.
_signal.Reset();
Thread.Sleep(1000);
Console.WriteLine("\n{0}/{1} threads received the signal.\n\n", _signalledCount, NUM_THREADS);
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
private static void test(int id)
{
Console.WriteLine("Thread " + id + " started.");
_startCounter.Signal();
_signal.Wait();
Interlocked.Increment(ref _signalledCount);
Console.WriteLine("Task " + id + " received the signal.");
}
private const int NUM_THREADS = 20;
private static readonly ManualResetEventSlim _signal = new ManualResetEventSlim();
private static CountdownEvent _startCounter;
private static int _signalledCount;
}
}
注意:这个问题提出了类似的问题,但似乎没有答案(除了确认是的,这可能发生)。
Issue with ManualResetEvent not releasing all waiting threads consistently
[编辑]
正如 Ian Griffiths 在下面指出的那样,答案是所使用的底层 Windows API 并非旨在支持这一点。
很遗憾the Microsoft documentation for ManualResetEventSlim.Set() 错误地声明它
将事件的状态设置为已发出信号,这允许一个或多个 等待事件继续进行的线程。
显然“一个或多个”应该是“零个或多个”。
【问题讨论】:
-
好的,我试了一下。没有睡眠,一个线程接收到信号。使用 Sleep(0),8 个线程,使用 Sleep(10),所有 20 个线程。所以,症状得到确认。
-
您只是使用了错误的同步对象,检测信号等待句柄需要操作系统线程调度程序运行。 Slim 版本更糟糕,它很苗条,因为它不调用操作系统。您在这里需要 Monitor.Pulse(),Monitor 类会一直跟踪等待的线程。 MRE 完全缺少的功能,因为它不可能提供公平保证。但是您已经从链接的副本中知道了这一点。
-
当然,调度程序确实在运行 - Set() 是一个系统调用。
-
是的,我在我的实际代码中使用了 Montor.PulseAll()(不是 Monitor.Pulse())。我只是想知道为什么它不起作用。
-
“胖”ManualResetEvent 出现同样的问题。
标签: c# multithreading