# Distributed arrays in for loop

**URL:** https://discourse.julialang.org/t/distributed-arrays-in-for-loop/118728
**Category:** General Usage
**Tags:** parallel
**Created:** [August 28, 2024, 5:48pm UTC](https://discourse.julialang.org/t/distributed-arrays-in-for-loop/118728 "2024-08-28T17:48:57Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![clempe](https://avatars.discourse-cdn.com/v4/letter/c/9de0a6/32.png) [@clempe](https://discourse.julialang.org/u/clempe)
#### Post date: [August 28, 2024, 5:48pm UTC](https://discourse.julialang.org/t/distributed-arrays-in-for-loop/118728/1 "2024-08-28T17:48:57Z")

</div>

Hi, I’m trying to get distributed arrays to work correctly for my distributed for loop. I’m getting this weird outcome where not all workers do their task always, even though I know they’ve been assigned correctly (using procs). Not sure what’s going on. Here a MWE:

```julia
using Distributed

addprocs(4)
@everywhere begin
    using DistributedArrays
    result_D = dzeros(Float64,(2,4), workers()[1:4],[1,4])
    initq = [i*ones(2,1) for i in 1:4]  
    @sync @distributed for ele in initq 
        res_local = localpart(result_D)
        res_local .= ele
    end
end

result = convert(Array,result_D)

```

When I run this, the results are inconsistent: sometimes the whole array stays empty, sometimes one worker does a job, sometimes a few. What could be the issue?

---

<div class="post-metadata">

### Author: ![abraemer](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/abraemer/32/51403_2.png) [@abraemer](https://discourse.julialang.org/u/abraemer)
#### Post date: [August 28, 2024, 8:54pm UTC](https://discourse.julialang.org/t/distributed-arrays-in-for-loop/118728/2 "2024-08-28T20:54:25Z")

</div>

I think you shouldn’t define the distributed array and run the `@distributed` loop inside the `@everywhere` block. This might cause the issues you see, since somehow every worker ends up allocating their own array and I am not sure which worker will then write where.

---

<div class="post-metadata">

### Author: ![clempe](https://avatars.discourse-cdn.com/v4/letter/c/9de0a6/32.png) [@clempe](https://discourse.julialang.org/u/clempe)
#### Post date: [August 28, 2024, 9:17pm UTC](https://discourse.julialang.org/t/distributed-arrays-in-for-loop/118728/3 "2024-08-28T21:17:15Z")

</div>

Thank you @abraemer ! This indeed did the trick. Here the working version:

```julia
using Distributed

addprocs(4)
@everywhere begin

    using Distributed, DistributedArrays
    initq = [i*ones(2,1) for i in 1:4] 
end
result_D = dzeros(Float64,(2,8), workers()[1:4],[1,4])
    
@sync @distributed for ele in initq 
    res_local = localpart(result_D)
    res_local .= ele
end
result = convert(Array,result_D)

```
