# Disappearing variable in parallel computations

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 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 I get as an output m, so Mathematica doesn't want to store my variable in the memory. If anyone has an idea why Mathematica behaves like this, please help.

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

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[]

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}];

• +1 for ParallelTable; in Mathematica you want to try and use functional language, not procedural language – 2012rcampion Mar 6 '15 at 19:55

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 as a bit of a kludge we can pull the values back to global like this:  Set @@@ ReleaseHold@Flatten@ParallelEvaluate@DownValues@x; x[#] & /@ Range  {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 a=Total@ParallelEvaluate[a]


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