Printing output of SharedArray


#1

Hi,
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:

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

for i = 1:3
	println(outpu[i])
end

arr = SharedArray{Int}(3)
for i = 1:3
	println(outpu[i])
end

(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?


#2

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.


#3

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: