# Writing to a shared buffer in multi-threaded for loop

**URL:** <https://discourse.julialang.org/t/writing-to-a-shared-buffer-in-multi-threaded-for-loop/137373>\
**Category:** Performance\
**Tags:** multithreading\
**Created:** [June 1, 2026, 1:18pm UTC](https://discourse.julialang.org/t/writing-to-a-shared-buffer-in-multi-threaded-for-loop/137373 "2026-06-01T13:18:46Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![stevengj](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stevengj/32/71_2.png) [@stevengj](https://discourse.julialang.org/u/stevengj)\
**Post date:** [June 1, 2026, 1:33pm UTC](https://discourse.julialang.org/t/writing-to-a-shared-buffer-in-multi-threaded-for-loop/137373/2 "2026-06-01T13:33:14Z")

</div>

> [@user664303](#):
>
> I don’t see a way to reduce TaskLocalValues after the for loop, since they get cleaned up.

TaskLocalValues.jl are just a thin wrapper around `Base.task_local_storage`, which provides more flexibility. Using the latter, when you create the local buffer for the first time in a given task, you could store it in a thread-global array (protected by a lock) to later reduce over, i.e. something like:

```julia-auto
buf = get!(task_local_storage(), :MY_BUFFER_SYMBOL) do
    # create new buffer if it doesn't exist yet for this task
    lock(my_buffers_lock) do
        newbuf = create_new_buffer()
        push!(my_buffers, newbuf)
        newbuf
    end
end::SomeBufferType

```

Alternatively, you can replace your threaded loop with a loop over equal-sized chunks of the array, via ChunkSplitters.jl, and allocate one buffer per chunk, as described here: [No more threadid indexing? [thread-local storage] - #13 by lmiq](https://discourse.julialang.org/t/no-more-threadid-indexing-thread-local-storage/131535/13) — the tradeoff is that this pushes more load-balancing responsibility onto you.

---

_[View the full topic](https://discourse.julialang.org/t/writing-to-a-shared-buffer-in-multi-threaded-for-loop/137373)._
