# Printing output of SharedArray

**URL:** https://discourse.julialang.org/t/printing-output-of-sharedarray/3008
**Category:** New to Julia
**Created:** [April 2, 2017, 11:25am UTC](https://discourse.julialang.org/t/printing-output-of-sharedarray/3008 "2017-04-02T11:25:41Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![samsamsam](https://avatars.discourse-cdn.com/v4/letter/s/8e7dd6/32.png) [@samsamsam](https://discourse.julialang.org/u/samsamsam)
#### Post date: [April 2, 2017, 11:25am UTC](https://discourse.julialang.org/t/printing-output-of-sharedarray/3008/1 "2017-04-02T11:25:41Z")

</div>

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:

```julia
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?

---

<div class="post-metadata">

### Author: ![xiaoweiz](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/xiaoweiz/32/2049_2.png) [@xiaoweiz](https://discourse.julialang.org/u/xiaoweiz)
#### Post date: [April 2, 2017, 12:50pm UTC](https://discourse.julialang.org/t/printing-output-of-sharedarray/3008/2 "2017-04-02T12:50:53Z")

</div>

I had a similar problem a couple of days ago ([Correct usage of SharedArray and @parallel?](https://discourse.julialang.org/t/correct-usage-of-sharedarray-and-parallel/2979)).

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.

---

<div class="post-metadata">

### Author: ![samsamsam](https://avatars.discourse-cdn.com/v4/letter/s/8e7dd6/32.png) [@samsamsam](https://discourse.julialang.org/u/samsamsam)
#### Post date: [April 2, 2017, 10:33pm UTC](https://discourse.julialang.org/t/printing-output-of-sharedarray/3008/3 "2017-04-02T22:33:01Z")

</div>

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 🙂
