【发布时间】:2014-11-12 03:23:59
【问题描述】:
我正在尝试使用AutoResetEvent 运行两组线程以相互协调;
在第一组(客户)完成后,我使用thread.join() 确保第一组中的所有线程都已完成,设置标志以停止第二个线程。但是,thread.join() 从未完成,调试器在两者之间失去了踪迹。该标志从未设置,因此它继续运行。
有人可以看看这里出了什么问题吗?谢谢!
private static AutoResetEvent tellerFree = new AutoResetEvent(true);
private volatile static bool doneflag = true;
public static void runMultTeller()
{
List<Thread> custThreads = new List<Thread>();
List<Thread> tellThreads = new List<Thread>();
for (int i = 1; i <= 50; i++)
{
Thread td = new Thread(getTeller);
td.Name = Convert.ToString(i);
custThreads.Add(td);
td.Start();
}
for (int j = 1; j <= 5; j++)
{
Thread tt = new Thread(doTelling);
tt.Name = Convert.ToString(j);
custThreads.Add(tt);
tt.Start();
}
foreach (Thread tc in custThreads)
{
if (tc.IsAlive)
{
tc.Join();
}
}
Console.WriteLine("Customer are done");
doneflag = false;
foreach (Thread t2 in tellThreads)
{
t2.Join();
}
Console.WriteLine("Teller are done");
Console.WriteLine("Done");
Thread.Sleep(5000);
}
static public void doTelling()
{
string name = Thread.CurrentThread.Name;
while (doneflag)
{
Console.WriteLine("teller#{0} serving", name);
Thread.Sleep(500);
Console.WriteLine("teller#{0} done", name);
tellerFree.Set();
}
}
static public void getTeller()
{
string name = Thread.CurrentThread.Name;
Console.WriteLine("customer#{0} Enter", name);
tellerFree.WaitOne();
Console.WriteLine("customer#{0} Leave", name);
}
【问题讨论】:
-
你不需要信号量吗?
-
如果你正在处理这些线程之间的生产者/消费者关系,我建议阅读this article。我不确定这是否是您故意的,但是按照您现在设置的方式,一个生产线程可能会释放所有 50 个消费线程。我想你希望一个线程产生的每个项目都被一个消费线程消费。如果没有,那我道歉。
-
感谢您的指出。在这个示例中,我没有尝试这样做。也许下次吧。
标签: c# multithreading join