2
$\begingroup$

I'm starting to use Mathematica's parallelization more frequently, and noticed an oddity I would appreciate to be explained. Please feel free to correct my terminology.

When on the main kernel, variables and functions defined will be passed through to parallel kernels. So running:

varA = 5;
ParallelDo[Print[varA], 3]

Will result in 3 prints of 5. However, when I use a dollar signed variable like $MinPrecision I see that running:

$MinPrecision = 1000;
Print[$MinPrecision]
ParallelDo[Print[$MinPrecision], 3]

Will result in 1 print of 1000, expected, and 3 prints of 0, weird. Of course this can be circumvented with ParallelEvaluate[$MinPrecision = 1000;], but when is ParallelEvaluate necessary and when isn't it?

$\endgroup$

1 Answer 1

2
$\begingroup$

Regarding parallelization, user defined variables are immediately passed to the parallel kernels. However with global constants, 'dollar sign variables' that are defined when the kernel starts (wording is necessary since you can create your own $MyGlobalConstant variable after the kernel starts), their values are not mutated by the main kernel. Parallel kernels also cannot mutate other kernels.

The code below should act as a good start to understanding how Mathematica handles parallelized functions like ParallelDo, ParallelSum, and ParallelEvaluate as understanding what each kernel does and doesn't have access to is crucial.

ClearAll["Global`*"];

(* Showing parallel cores inheret main kernel variables
   and mutation after first definition *)
varA = 5;
ParallelEvaluate[Print[varA]];
varA = 10;
ParallelEvaluate[Print[varA]];

(* Showing Mathematica Global Constants must be mutated in
   ParallelEvaluate *)
$MinPrecision = 1000;
ParallelEvaluate[Print[$MinPrecision]];

(* Showing parallel kernels can't mutate the main kernel's
   variables *)
ParallelEvaluate[varA = 15]
Print[varA]

Did not expect to answer my own question but hope this helps someone else struggling with parallelizing code.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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