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);
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) });or
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.