[英]How can I synchronize multiple threads
I wrote this console program: 我写了这个控制台程序:
static void Main(string[] args)
{
object sync = new object();
Thread[] t = new Thread[10];
int count = 0;
for (var i = 0; i < t.Length; i++)
{
t[i] = new Thread(() =>
{
lock (sync)
{
int inc = count;
Console.WriteLine("Count: {0}", count);
count = inc + 1;
}
});
}
foreach (var t1 in t)
{
t1.Start();
}
foreach (var t1 in t)
{
t1.Join();
Console.WriteLine("\nFinal Count= {0}", count);
Console.ReadKey();
}
}
I get this result in the output : 我在输出中得到这个结果:
Count: 0
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Count: 6
Count: 7
Final Count= 7
Count: 8
Count: 9
and when I run the app multiple time I'm getting more different results but I want to see this result : 当我多次运行该应用程序时,我得到了更多不同的结果,但我想看到以下结果:
Count: 0
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Count: 6
Count: 7
Count: 8
Count: 9
Final Count= 10
why does it return different results and how do I fix this? 为什么返回不同的结果?如何解决?
Try do don't manually create/terminate threads like this, it's a time consuming operation and it doesn't scale well. 尝试不要像这样手动创建/终止线程,这是一项耗时的操作,并且伸缩性不佳。
Use the ThreadPool
instead. 请改用ThreadPool
。
Or better: use tasks , and synchronize them by using await Task.WhenAll(list of your tasks)
或更好:使用task ,并使用await Task.WhenAll(list of your tasks)
同步它们
Well, instead of this : 好吧,代替这个:
foreach (var t1 in t)
{
t1.Join();
Console.WriteLine("\nFinal Count= {0}", count);
Console.ReadKey();
}
You should write: 您应该写:
foreach (var t1 in t)
{
t1.Join();
}
Console.WriteLine("\nFinal Count= {0}", count);
Console.ReadKey();
Otherwise you will have a racing and your code will be undeterministic. 否则,您将参加比赛,并且代码不确定。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.