的Parallel.For():循环外更新变量 [英] Parallel.For(): Update variable outside of loop
问题描述
我只是在寻找到新的.NET 4.0功能。就这样,我试图用一个简单的计算的Parallel.For
和正常为(X,X,X)
循环。
I'm just looking in to the new .NET 4.0 features. With that, I'm attempting a simple calculation using Parallel.For
and a normal for(x;x;x)
loop.
不过,我得到不同的结果,约50%的时间。
However, I'm getting different results about 50% of the time.
long sum = 0;
Parallel.For(1, 10000, y =>
{
sum += y;
}
);
Console.WriteLine(sum.ToString());
sum = 0;
for (int y = 1; y < 10000; y++)
{
sum += y;
}
Console.WriteLine(sum.ToString());
我的猜测是,线程试图更新求和在同一时间。
有没有办法解决它的一个明显的方式?
My guess is that the threads are trying to update "sum" at the same time.
Is there an obvious way around it?
推荐答案
您无法做到这一点。 之
正在穿过你的并行线程共享。你需要确保的之
变量只由一个线程在同一时间访问:
You can't do this. sum
is being shared across you parallel threads. You need to make sure that the sum
variable is only being accessed by one thread at a time:
// DON'T DO THIS!
Parallel.For(0, data.Count, i =>
{
Interlocked.Add(ref sum, data[i]);
});
但...这是一个反模式,因为你已经有效地序列化的循环,因为每个线程都在锁定 Interlocked.Add
。
您需要做的就是添加子汇总,并在年底这样的合并它们:
What you need to do is add sub totals and merge them at the end like this:
Parallel.For<int>(0, result.Count, () => 0, (i, loop, subtotal) =>
{
subtotal += result[i];
return subtotal;
},
(x) => Interlocked.Add(ref sum, x)
);
您可以找到这个MSDN上进一步讨论:<一href="http://msdn.microsoft.com/en-us/library/dd460703.aspx">http://msdn.microsoft.com/en-us/library/dd460703.aspx
You can find further discussion of this on MSDN: http://msdn.microsoft.com/en-us/library/dd460703.aspx
插头::您可以找到更多关于这在指南并行编程
PLUG: You can find more on this in Chapter 2 on A Guide to Parallel Programming
下面是也绝对值得一读...
The following is also definitely worth a read...
<一个href="http://www.microsoft.com/downloads/details.aspx?FamilyID=86b3d32b-ad26-4bb8-a3ae-c1637026c3ee&displaylang=en">Patterns并行编程:了解和应用并行模式与.NET Framework 4 - 斯蒂芬Toub
这篇关于的Parallel.For():循环外更新变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!