1
$\begingroup$

This is a simplified example of a problem I ran into. I want to count how often a subkernel executes a given computation. So, after having launched the subkernels, I construct an association with each $KernelID as a key and the number of executions as a value. Here is the construction of the initial value of that association:

SetSharedVariable[asc];
asc={};ParallelDo[AppendTo[asc,$KernelID], {i,1,$KernelCount}];
asc= KeySort[Association[#->0& /@ asc]]

(* <|1->0,2->0,3->0,4->0|> *)

I expected the following to work:

ParallelDo[
  Pause[RandomReal[{0.2, 3}]];
  Print[{$KernelID, asc[$KernelID]}];
  asc[$KernelID]++,
{i,1,2}];
asc

But the result was

(kernel 3) {3,0}
(kernel 3) Set::noval: Symbol asc in part assignment does not have an immediate value.
(kernel 4) {4,0}
(kernel 4) Set::noval: Symbol asc in part assignment does not have an immediate value.
Out[40]= <|1->0,2->0,3->0,4->0|>

Despite the fact that the value is printed, the message says that there is no immediate value of the association, and nothing is assigned to the key. Is this a bug, or did I something wrong?

I found a workaround:

ParallelDo[
  Pause[RandomReal[{0.2,3}]];
  AppendTo[asc, $KernelID->asc[$KernelID]+1],
 {i,1,20}];
asc

(* <|4->3,2->5,3->7,1->5|> *)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.