# Reusing @local cache when multithreading

**URL:** <https://discourse.julialang.org/t/reusing-local-cache-when-multithreading/136579>\
**Category:** Performance\
**Tags:** question, performance, multithreading, memory-allocation, task\_local\_storage\
**Created:** [April 5, 2026, 9:53pm UTC](https://discourse.julialang.org/t/reusing-local-cache-when-multithreading/136579 "2026-04-05T21:53:02Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![amousavi](https://avatars.discourse-cdn.com/v4/letter/a/bbce88/32.png) [@amousavi](https://discourse.julialang.org/u/amousavi)\
**Post date:** [April 5, 2026, 9:53pm UTC](https://discourse.julialang.org/t/reusing-local-cache-when-multithreading/136579/1 "2026-04-05T21:53:02Z")

</div>

Hi everyone! I am trying to update an old project of mine where I have three nested for loops as such:

```julia
scratch = zeros(Float32, tree_nodes, nthreads())
collect_here = zeros(Float32, nthreads())
for i in eachindex(V)
  @threads for j in eachindex(M)
    @views collect_here[threadid()] = tree_traversal!(scratch[:, threadid()], tree)
  end
  result = do_stuff(collect_here)
  ...
end

```

Where `tree_traversal!` does considerable work on a binary tree and needs a relatively large amount of scratch memory. In this old setting I was able to just allocate the memory in one go beforehand and I could avoid relying on locking mechanisms. After moving to `OhMyThreads` and setting up my scratch memory in `@local`, I am now spending approximately 20% of my time in the task allocating this memory (from `@btime`), which is a penalty I cannot really afford… ☹ I am aware of the option of using the `:static` scheduler, but would like to avoid this.

```julia
using OhMyThreads

for i in eachindex(V)
  collect_here = @tasks for j in eachindex(M)
    @set collect = true
    @local scratch = zeros(Float32, tree_nodes)
    tree_traversal!(scratch, tree)
  end
  result = do_stuff(collect_here)
  ...
end

```

Is there any sort of well-supported way of setting up some sort of pool for scratch memory, where this allocated scratch memory can be reused between tasks in different iterations of the outer loop? Or am I stuck having to allocate this memory in every such iteration.

---

<div class="post-metadata">

**Author:** ![Ralph\_Smith](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/ralph_smith/32/10344_2.png) [@Ralph\_Smith](https://discourse.julialang.org/u/Ralph_Smith)\
**Post date:** [April 6, 2026, 1:30am UTC](https://discourse.julialang.org/t/reusing-local-cache-when-multithreading/136579/3 "2026-04-06T01:30:17Z")

</div>

Did you try the `Channel`-based scheme described in [the OhMyThreads docs](https://juliafolds2.github.io/OhMyThreads.jl/stable/literate/tls/tls/#The-safe-way:-Channel)? That seems to suit your workload. It does use locks under the hood, but the user doesn’t have to think about them.
