Consider this code:
f[i_] := Sin[i]
Do[array1[i] = f[i], {i, 1, 5}]
Table[array1[i], {i, 1, 5}]
Returns:
{Sin[1], Sin[2], Sin[3], Sin[4], Sin[5]}
Now, I want to parallelize my code:
ParallelDo[array2[i] = f[i], {i, 1, 5}]
Table[array2[i], {i, 1, 5}]
Returns:
{array2[1], array2[2], array2[3], array2[4], array2[5]}
The parallelized version is unevaluated.
How can I resolve the issue? I used SetSharedFunction[f]
but it did not work.
SetSharedFunction
for the most expensive part of the code inDo
, so have not only negated all benefits of parallelization, but made the code (considerably) slower.SetSharedFunction
forces the function to be evaluated on the main kernel, i.e. almost the same as a non-parallelDo
except that in this case instead of evaluating something directly on the main kernel, the main kernel is asking the subkernel to ask the main kernel to evaluate a piece of code. This introduces considerable overhead. $\endgroup$ – Szabolcs Nov 5 '14 at 17:27Do
withParallelDo
, but think about what the subkernels would need to do precisely (and how they need to communicate) to achieve your goal, i.e. design it as a parallel algorithm from the start. $\endgroup$ – Szabolcs Nov 5 '14 at 18:39