Printing output of SharedArray

When I print the output of a shared array that I’ve populated with integers, the output is all zeros, unless I define another shared array before I start printing…

In particular, I run this code:

outpu = SharedArray{Int}(3)
@parallel for i = 1:3
	outpu[i] = i

for i = 1:3

arr = SharedArray{Int}(3)
for i = 1:3

(which is a highly simplified version of what I’m actually trying to do), and the output is this:
0 0 0 1 2 3

If I comment out the line arr = SharedArray{Int}(3) then the output is all zeros. So it seems that I have to define another shared array before println works as expected. I’m using the work around at the moment (defining another shared array), but can someone explain this behavior all the same?

I had a similar problem a couple of days ago (Correct usage of SharedArray and @parallel?).

Basically, you need to add @sync in front of @parallel to force the available threads wait for the end of loop operations before doing something else.


Thanks. So the @sync macro makes the main thread wait for the @parrallel loop to finish. That fixes it.

In my case, defining another shared array (and running another loop) must have slowed down the main thread enough to let the parallel loop finish.

Lines that don’t execute in the order they’re written is going to take some getting used to :slight_smile: