4
$\begingroup$

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?

$\endgroup$
0

2 Answers 2

3
$\begingroup$

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.

$\endgroup$
2
$\begingroup$

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}
$\endgroup$
3
  • $\begingroup$ 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! $\endgroup$ Dec 24, 2014 at 15:30
  • $\begingroup$ 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. :) $\endgroup$
    – ChadK
    Dec 24, 2014 at 16:13
  • 1
    $\begingroup$ 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. :) $\endgroup$ Dec 24, 2014 at 16:51

Your Answer

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

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