# Work array for parallel loop

**URL:** <https://discourse.julialang.org/t/work-array-for-parallel-loop/88546>\
**Category:** General Usage\
**Created:** [October 10, 2022, 11:50pm UTC](https://discourse.julialang.org/t/work-array-for-parallel-loop/88546 "2022-10-10T23:50:42Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![Stephen\_Vavasis](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stephen_vavasis/32/3389_2.png) [@Stephen\_Vavasis](https://discourse.julialang.org/u/Stephen_Vavasis)\
**Post date:** [October 10, 2022, 11:50pm UTC](https://discourse.julialang.org/t/work-array-for-parallel-loop/88546/1 "2022-10-10T23:50:42Z")

</div>

I’m investigating parallelization of some loops in an older code of mine. The structure is like this:

```julia
work_vector = zeros(small_size)
for i = 1 : big_size
    x = big_vector1[i]
    # ...
    # compute y from x using work_vector for scratch space
    # ...
    big_vector2[i] = y
end

```

I think that if I just insert `Threads.@threads` in front of the `for` loop, this will end badly because the threads will collide on the work array. What is the recommended approach?

---

<div class="post-metadata">

**Author:** ![lmiq](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/lmiq/32/18314_2.png) [@lmiq](https://discourse.julialang.org/u/lmiq)\
**Post date:** [October 10, 2022, 11:57pm UTC](https://discourse.julialang.org/t/work-array-for-parallel-loop/88546/2 "2022-10-10T23:57:04Z")

</div>

One way is to create a copy of the work vector for each thread.

This small package can help then  
to write the loop: [GitHub - m3g/ChunkSplitters.jl: Simple chunk splitters for parallel loop executions](https://github.com/m3g/ChunkSplitters.jl)

---

<div class="post-metadata">

**Author:** ![Stephen\_Vavasis](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stephen_vavasis/32/3389_2.png) [@Stephen\_Vavasis](https://discourse.julialang.org/u/Stephen_Vavasis)\
**Post date:** [October 11, 2022, 1:48am UTC](https://discourse.julialang.org/t/work-array-for-parallel-loop/88546/3 "2022-10-11T01:48:37Z")

</div>

Just to be clear: the solution you are proposing is like this:

```julia
Threads.@threads for (irange, _) in chunks(big_vector1, 10, :batch)
    work_vector = zeros(small_size)
    for i in irange
        x = big_vector1[i]
        # compute y from x using work_vector for scratch
        big_vector2[i] = y
    end
end

```

---

<div class="post-metadata">

**Author:** ![lmiq](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/lmiq/32/18314_2.png) [@lmiq](https://discourse.julialang.org/u/lmiq)\
**Post date:** [October 11, 2022, 2:00am UTC](https://discourse.julialang.org/t/work-array-for-parallel-loop/88546/4 "2022-10-11T02:00:08Z")

</div>

Yes. That or allocating a vector of work vectors outside the threaded loop (if you want to preserve that allocation).
