Message Boards Message Boards

1
|
4215 Views
|
2 Replies
|
2 Total Likes
View groups...
Share
Share this post:

SetSharedVariable of an Association

Using a list

Let's consider the working example:

ClearAll[GetPrimes2]
GetPrimes2[n_Integer] := Module[{pos},
  pos = FirstPosition[vals[[All, 1]], $KernelID][[1]];
  vals[[pos, 2]] += 1;
  FactorInteger[n]
  ]
CloseKernels[];
LaunchKernels[4];

vals = {#, 0} & /@ ParallelEvaluate[$KernelID];
Dynamic[vals]

tasks = Range[1000];
DistributeDefinitions[GetPrimes2, vals];
SetSharedVariable[vals]
ParallelMap[GetPrimes2, tasks]

Where we have the variable val, where each element of it is a list of two elements {kernel ID, counter}. Now in the parallel evaluation when a kernel does a job I want it to add one to the counter.

This works and when you execute you see the counter dynamically update.

Using an association

Now rather than using a list of {kernel ID, counter} we could use an association:
<|kernel ID -> counter ,kernel ID -> counter......|>

ClearAll[GetPrimes]
GetPrimes[n_Integer] := Module[{},
  vals[$KernelID] += 1;
  FactorInteger[n]
  ]
CloseKernels[];
LaunchKernels[4];

vals = Association @@ (# -> 0 & /@ ParallelEvaluate[$KernelID]);
Dynamic[vals]

tasks = Range[1000];
DistributeDefinitions[GetPrimes, vals];
SetSharedVariable[vals]
ParallelMap[GetPrimes, tasks]

However this does not work. Can someone explain me why I can not use an Association here? Is this expected behavior, a bug, lack of implementation, my error, or … ?

POSTED BY: Sander Huisman
2 Replies

I can't say whether this is expected behavior - I think it's definitely worth reporting as a bug.

But as a workaround, instead of using the operator-like syntax

vals[$KernelID]++

use Part syntax:

vals[[ Key[$KernelID] ]]++

and it behaves correctly - with the Dynamic association updating in real time.

POSTED BY: Jason Biggs

Thank you so much! not sure if this a bug or just not supported indeed! Thanks for a solution!

POSTED BY: Sander Huisman
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract