2
$\begingroup$

Is it possible to parallelize a code with this structure?

n=0;
Do[If[condition, n++],{100}]
n

ParallelDo always returns n=0.

$\endgroup$
7
$\begingroup$

Mathematica implements distributed memory parallelism. Memory cannot be shared between parallel threads. Thus, strictly speaking, the answer is no. Each parallel thread will have a separate n.

SetSharedVariable will let you pretend that n is shared between the parallel kernels, but this is not what really happens. n will instead be always evaluated in on the main kernel. This means that every time n is read or written, a callback to the main kernel is necessary. This will often have a very large performance impact, and is not typically a workable solution (unless your condition takes a very long time to evaluate).

What one normally does is think not in terms of a specific algorithm, but in terms of the problem that needs to be solved. Try to come up with a solution that requires no communication between the parallel kernels. It seems to me that you want to count how many times of 100 is a condition satisfied. Well, break that 100 down into 4 groups, each having 25 iterations, and count separately in each group. The add up the counts at the end. ParallelCombine does this quite directly, but it can be implemented with other parallel constructs as well.

To give a specific example, the following code counts how many times the condition RandomReal[] < 0.3 is satisfied out of 10000 trials.

Total@ParallelTable[
  If[RandomReal[] < 0.3, 1, 0],
  {10000}
]
$\endgroup$
  • $\begingroup$ Is something like this correct? ParallelCombine[Do[If[condition, n++],{100}]] $\endgroup$ – mattiav27 Sep 5 '18 at 10:06
  • $\begingroup$ @mattiav27 I'm sorry to have to ask this, but have you looked at the ParallelCombine documentation? I don't understand how you came to the conclusion that this would be correct based on the documentation page. $\endgroup$ – Szabolcs Sep 5 '18 at 10:09
  • $\begingroup$ @mattiav27 Also, if you don't understand parts of my answer, that's fine. Just ask (be specific), and I'll try to clarify. But please do follow the links and do read through all of the answer. I tried to explain why it is not possible to use the n variable the way you were trying to. In this comment you are trying to use it the same way. $\endgroup$ – Szabolcs Sep 5 '18 at 10:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.