2
$\begingroup$

I have a problem with parallel computations. When I try to evaluate formula like this:

Do[m[i]=2,{i,1,10}]

and then I try to call for instance m[1] I get as an output 2, so everything is all right. But when I do parallel computations and use the formula

Parallelize[Do[m[i] = 2, {i, 1, 10}]] 

and then call the argument m[1] I get as an output m[1], so Mathematica doesn't want to store my variable in the memory. If anyone has an idea why Mathematica behaves like this, please help.

$\endgroup$
4
$\begingroup$

As you are changing the DownValues of m inside your ParallelDo you have to share them among the parallel kernels using SetSharedFunction first:

SetSharedFunction[m]

Parallelize[Do[m[i] = 2, {i, 1, 10}]]

m[1]
2

As you refer to m as a variable, something like

m = ConstantArray[0, 10]
SetSharedVariable[m]
Parallelize[Do[m[[i]] = 2, {i, 1, 10}]]
m[[1]]
2

might be more appropriate.
But probably trying to ovoid using Do might be the better solution in that case:

m = ParallelTable[2, {i, 1, 10}];
$\endgroup$
  • $\begingroup$ +1 for ParallelTable; in Mathematica you want to try and use functional language, not procedural language $\endgroup$ – 2012rcampion Mar 6 '15 at 19:55
2
$\begingroup$

This is not likely a practical approach, but it illustrates whats going on:

 Clear[x];
 ParallelDo[x[i] = i^2, {i, 1, 10}];

as noted the global x has not been defined, however each of our kernels retains the definition:

 ParallelEvaluate[{$KernelID, DownValues[x]}] // MatrixForm

enter image description here

as a bit of a kludge we can pull the values back to global like this:

 Set @@@ ReleaseHold@Flatten@ParallelEvaluate@DownValues@x;
 x[#] & /@ Range[10]

{1, 4, 9, 16, 25, 36, 49, 64, 81, 100}

similarly for lists:

 a = ConstantArray[0, 10];
 ParallelDo[a[[i]] = i^2, {i, 1, 10}];
 ParallelEvaluate[{$KernelID, a}] // MatrixForm

enter image description here

 a=Total@ParallelEvaluate[a]

{1, 4, 9, 16, 25, 36, 49, 64, 81, 100}

$\endgroup$

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.