在不同的场合给出不同的结果

本文关键字:结果 | 更新日期: 2023-09-27 18:02:11

我从来没有使用过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();

我认为这与线程相互工作有关,但这似乎是一个错误

注意,我确实看了一下模拟给出了不同的结果,正常的for循环Vs Parallel for
为什么会发生这种情况?

在不同的场合给出不同的结果

因为这段代码定义不清:

 Parallel.ForEach<int, long>(nums,() => 0,(j, loop, subtotal) =>
 {
   subtotal += 1;
   subtotal *= 2;
   return subtotal;
 },(finalResult) => Interlocked.Add(ref total, finalResult));

在这种情况下,如果一个线程执行两个迭代,那么你得到结果6。实际上,你可以:

subTotal = 0; //From init
subTotal += 1; //=1 First iteration
subTotal *= 2; //=2 First iteration
subTotal += 1; //=3 Second iteration
subTotal *= 2; //=6 Second iteration
total += subTotal; //=6 End gathering (actually interlocked)

但是如果两个线程共享工作,则得到

subTotal1 = 0; //From init
subTotal2 = 0; //From init
subTotal2 += 1; //=1
subTotal1 += 1; //=1
subTotal1 *= 2; //=2
subTotal2 *= 2; //=2
total += subTotal1 //=2 End gathering 1 (interlocked)
total += subTotal2 //=4 End gathering 2 (interlocked)