并行编程互锁 C#
的示例感到困惑
我对http://msdn.microsoft.com/en-us /library/dd997393.aspx
Parallel.ForEach<int, long>(nums, // source collection
() => 0, // method to initialize the local variable
(j, loop, subtotal) =>
{
subtotal += nums[j];
return subtotal;
},
(finalResult) => Interlocked.Add(ref total,finalResult) );
我不知道为什么最后一个委托 (finalResult) => Interlocked.Add(参考总计,最终结果)
需要互锁,而前面的表达式
(j, loop, subtotal) =>
{
subtotal += nums[j];
return subtotal;
},
不需要?
谢谢
Im confused with the example at
http://msdn.microsoft.com/en-us/library/dd997393.aspx
Parallel.ForEach<int, long>(nums, // source collection
() => 0, // method to initialize the local variable
(j, loop, subtotal) =>
{
subtotal += nums[j];
return subtotal;
},
(finalResult) => Interlocked.Add(ref total,finalResult) );
I dont know why the last delegate (finalResult) => Interlocked.Add(ref total,finalResult)
requires an Interlock, whereas the previous expression
(j, loop, subtotal) =>
{
subtotal += nums[j];
return subtotal;
},
does not?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Parallel.For()
和Parallel.ForEach()
方法使用 Partitioner。在 10,000 个单独的任务上执行超过 10,000 个元素的循环效率非常低。分区器将数据分割成段,理想情况下ForEach()
将在 4 核 CPU 上的 2,500 个元素的 4 个任务(线程)中执行。有时这需要一些启发,您可以编写自己的自定义分区程序。当使用
ForEach()
的“正常”(简单)重载时,这是完全透明的。但是您的示例使用了表面分区的
重载之一。subtotal += nums[j];
语句在 1 个分区内迭代,因此是线程安全的。并且
(finalResult) => Interlocked.Add(ref Total,finalResult)
是分区合并的地方,这部分当然不是线程安全的。The
Parallel.For()
andParallel.ForEach()
methods make use of a Partitioner. It would be very inefficient to execute a loop over 10,000 elements on 10,000 individual Tasks. The partitioner splits the data in segments and ideally theForEach()
will execute in 4 Tasks (threads) of 2,500 elements on a 4-core CPU. This sometimes requires some heuristics and you can write your own custom-partitioner.When using the 'normal' (simple) overloads of
ForEach()
this is fully transparent. But your example uses one of the<TLocal>
overloads that surfaces the partitioning.The
subtotal += nums[j];
statement is iterated inside 1 partition and is therefore thread-safe.And
(finalResult) => Interlocked.Add(ref total,finalResult)
is where the partitions are merged, this part is of course not thread-safe.变量
subtotal
是只有一个线程可以访问的“本地数据”。另一方面,total 是一个所有线程都可以修改的变量,并且可能有多个线程可能会尝试同时更新总计。
The variable
subtotal
is "local data" that only one thread has access to.On the other hand,
total
is a variable that all the threads can modify, and potentially several threads may try to update the total at the same time.