# How to share numbered variables between kernels

Supose I have two variables v[1] and v[2]. I used:

SetSharedVariable[{v[1], v[2]}]


Then, I used:

$SharedVariables (*{}*)  It seems that in this way I can't share these two variables among the kernels. However, when I use: SetSharedVariable[{a, b}]  and then: $SharedVariables
{Hold[a], Hold[b]}


it's possible to share a and b.

Why can't I share v[1] and v[2] but it's possible to do it for a and b?

I believe that v[1] is a DownValue of a function v, not a variable. Thus, it should be shared among Kernels by means of SetSharedFunction

SetSharedFunction[v]


See SetSharedFunction and DownValues for examples of usage.

The reason this doesn't work is that you have defined v as a function, not a variable. If you want v to be a variable, then to access its elements one uses v[[1]] and v[[2]].

With your current definition, you can still share the values, but you need to use SetSharedFunction on v.

SetSharedFunction[v]
v[1] = 1;
v[2] = 2;


Parallel evaluations will now work with the function v. For example:

In[6]:= ParallelEvaluate[v[\$KernelID]]
Out[6]= {1, 2}

• Well, it's a false distinction to call it a "function" or a "variable", because these objects do not really exist in Mathematica, which is a term-rewriting system. What we have here are downvalues, as opposed to ownvalues. This was clear in the original PCT, which used names that make sense in the natural context of Mathematica, rather than using "simplified" names that are meaningless except to people who are familiar only with other languages! – Oleksandr R. Dec 24 '14 at 15:30
• Apologies for the laziness in my answer. Given that the relevant Mathematica functions for this question are called SetSharedFunction and SetSharedVariable, I assumed this level of explanation would be sufficient. Apparently that is not the case. :) – ChadK Dec 24 '14 at 16:13
• The answer is fine as far as it goes--I just don't feel that we should take the assertions of the documentation(which you repeat here) too seriously in this case, because it will ultimately lead to confusion. This is not meant as a criticism of you... unless you were the one responsible for having SharedDownValues renamed as SetSharedFunction in version 7. :) – Oleksandr R. Dec 24 '14 at 16:51