问题描述
我需要并行化确实在列表中的元素详尽的两两比较的方法。串行实现是直接的:
I need to parallelize a method that does an exhaustive pairwise comparison on elements in a list. The serial implementation is straight-forward:
foreach (var element1 in list)
foreach (var element2 in list)
foo(element1, element2);
在这种情况下,foo将不会改变的中element1或者element2的状态。我知道这是不是安全的,简单地做嵌套Parallel.ForEach语句:
In this case, foo won't alter the state of element1 or element2. I know it's not safe to simply do nested Parallel.ForEach statements:
Parallel.ForEach(list, delegate(A element1)
{
Parallel.ForEach(list, delegate(A element2)
{
foo(element1, element2);
});
});
什么是实现这个使用并行任务库的理想方式?
What would be the ideal way to implement this using the parallel tasks library?
推荐答案
你不能只是有一个并行接口和一个正常的循环?因此,无论
Couldn't you just have one Parallel and one normal loop? So either
Parallel.ForEach(list, delegate(A element1)
{
foreach(A element2 in list)
foo(element1, element2)
});
或
foreach(A element1 in list)
{
Parallel.ForEach(list, delegate(A element2)
{
foo(element1, element2);
});
}
应该加快步伐为好。有永远不会是每个周期一个线程,无论如何,所以这很可能是一样快或比嵌套并行循环稍微慢一些。
Should speed it up as well. There was never going to be a thread per cycle anyway, so this would probably be just as fast or slightly slower than nested parallel loops.
这篇关于嵌套Parallel.ForEach环路同一名单上吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!