【发布时间】:2016-08-12 07:21:59
【问题描述】:
我从未使用过Parallel.ForEach,但我玩过它并发现了这种情况。
我运行一个并行循环(在 msdn https://msdn.microsoft.com/en-us/library/dd997393(v=vs.110).aspx 上找到的代码确实使用 subtotal *=2 对其进行了编辑,以尝试了解它在做什么)首先使用可枚举范围 (0,1) 然后 (0,1,2) 然后我运行第二个再一次,但在线程休眠 200 毫秒后,结果就不同了
如果Thread.sleep(200)没有被注释掉,这就是结果
result 1 = 2
result 2 = 6
result 3 = 4
如果Thread.sleep(200)被注释掉,这就是结果
result 1 = 2
result 2 = 6
result 3 = 6
这里是代码
Stopwatch timer = new Stopwatch();
int[] nums = Enumerable.Range(0, 1).ToArray();
long total = 0;
for (int i = 0; i < 2; i++)
{
timer.Restart();
total = 0;
if (i == 0) nums = Enumerable.Range(0, 1).ToArray();
if (i == 1) nums = Enumerable.Range(0, 2).ToArray();
Parallel.ForEach<int, long>(nums,() => 0,(j, loop, subtotal) =>
{
subtotal += 1;
subtotal *= 2;
return subtotal;
},(finalResult) => Interlocked.Add(ref total, finalResult));
Console.WriteLine("The total from Parallel.ForEach is {0:N0} and took {1}", total, timer.Elapsed);
timer.Stop();
//Thread.Sleep(200);
}
timer.Restart();
nums = Enumerable.Range(0, 2).ToArray();
total = 0;
Parallel.ForEach<int, long>(nums, () => 0, (j, loop, subtotal) =>
{
subtotal += 1;
subtotal *= 2;
return subtotal;
},(finalResult) => Interlocked.Add(ref total, finalResult));
Console.WriteLine("The total from Parallel.ForEach is {0:N0} and took {1}", total, timer.Elapsed);
timer.Stop();
我认为这与线程相互工作有关,但这似乎是一个错误
注意我确实看过Simulation gives different result with normal for loop Vs Parallel For
为什么会这样?
【问题讨论】:
-
@JánЯabčan 你能详细说明一下吗?我不明白这段代码在什么时候乘以 2 以及为什么?
-
我什至不明白你是如何得到结果的......
-
@sam 把你的 thread.sleep 改成 1000 看看能不能搞定
-
我不明白应该看什么变量才能看到结果 2,6,4 或 2,6,6
-
@sam 将此代码复制到控制台应用程序中并运行它......它是总变量。如果您正在单步执行代码,则您正在创建自己的 thread.sleep,这意味着您永远不会看到 2,6,6 结果