# Best practice for threading nested loops

**URL:** https://discourse.julialang.org/t/best-practice-for-threading-nested-loops/102492
**Category:** New to Julia
**Created:** [August 4, 2023, 3:32pm UTC](https://discourse.julialang.org/t/best-practice-for-threading-nested-loops/102492 "2023-08-04T15:32:51Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![james3](https://avatars.discourse-cdn.com/v4/letter/j/b5e925/32.png) [@james3](https://discourse.julialang.org/u/james3)
#### Post date: [August 4, 2023, 3:32pm UTC](https://discourse.julialang.org/t/best-practice-for-threading-nested-loops/102492/1 "2023-08-04T15:32:51Z")

</div>

I was previously using Threads on a nested loop as follows

```julia
Threads.@threads for (aₓ, bₓ) in collect(Iterators.product(1:N.A, 1:N.B))
   ...
end

```

This works, but `collect(Iterators.product(1:N.A, 1:N.B))` is allocating. I can instead do

```julia
LoopIndices = CartesianIndices((N.A, N.B))
Threads.@threads for abₓ in LoopIndices
    (aₓ, bₓ) = Tuple(LoopIndices[abₓ])
    ...
end

```

which is not allocating, but a bit cumbersome. Is there a better way to achieve this?

---

<div class="post-metadata">

### Author: ![Sukera](https://avatars.discourse-cdn.com/v4/letter/s/ce7236/32.png) [@Sukera](https://discourse.julialang.org/u/Sukera)
#### Post date: [August 4, 2023, 4:49pm UTC](https://discourse.julialang.org/t/best-practice-for-threading-nested-loops/102492/2 "2023-08-04T16:49:26Z")

</div>

Do the patterns suggested in this recent blogpost help?

> **[PSA: Thread-local state is no longer recommended](https://julialang.org/blog/2023/07/PSA-dont-use-threadid/)**
>
> PSA: Thread-local state is no longer recommended; Common misconceptions about threadid() and nthreads()
