它以与 0.1、0.2、1、2.3 等相同的概率打印正确的结果 4.5。它有什么问题?
double average = 0;
Parallel.ForEach(
Enumerable.Range(0, 10),
() => 0,
(elem, loopState, localSum) => {
localSum += elem;
return localSum;
},
localSum => {
double localAvg = localSum / 10.0;
Interlocked.Exchange(ref average, localAvg);
}
);
Console.WriteLine($"Average in parallel manner: {average}");
例如:
平均并行方式:0,2
平均并行方式:3,2
平均并行方式:1,2
但是当我使用类似的代码时一切正常Interlocked.Add():
int totalSum = 0;
Parallel.For(0, 10, () => 0, (ind, loopState, local) => {
local += ind;
return local;
},
local => Interlocked.Add(ref totalSum, local));
Console.WriteLine($"Total sum in parallel manner: {totalSum}");
FFIVE
相关分类