# Optionally multi threaded for loop

**URL:** <https://discourse.julialang.org/t/optionally-multi-threaded-for-loop/81902>\
**Category:** Performance\
**Tags:** question\
**Created:** [May 30, 2022, 7:51am UTC](https://discourse.julialang.org/t/optionally-multi-threaded-for-loop/81902 "2022-05-30T07:51:19Z")\
**Posts on this page:** 1\
**Showing post:** 8

<div class="post-metadata">

**Author:** ![oxinabox](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/oxinabox/32/206603_2.png) [@oxinabox](https://discourse.julialang.org/u/oxinabox)\
**Post date:** [May 30, 2022, 6:36pm UTC](https://discourse.julialang.org/t/optionally-multi-threaded-for-loop/81902/8 "2022-05-30T18:36:44Z")

</div>

I suggest that it is probably worth using one of the packages that provide more detailed threading functionality, and expose it as functions. Such as [ThreadsX.jl](https://github.com/tkf/ThreadsX.jl)  
The `@threads` macro in particular is kind of a legacy from before Julia had first class, user extensible, threading.  
It has some advantages but not a lot.  
(Julia, like LaTeX and unlike say C# or Python; is absolutely not batteries included. Many of the best things live in packages. But julia’s package manager makes it easy to install packages and makes their compat safe.)

With ThreadX.jl you can do:

```julia
using ThreadsX

function foo(multi_thread=true)
    _foreach = multi_thread ? ThreadsX.foreach : Base.foreach
    _foreach(1:10) do ii
        @show ii
    end
end

```

which works:

```julia
julia> foo(false)
ii = 1
ii = 2
ii = 3
ii = 4
ii = 5
ii = 6
ii = 7
ii = 8
ii = 9
ii = 10

julia> foo(true)
ii = 1
ii = 9
ii = 6
ii = 3
ii = 7
ii = 8
ii = 10
ii = 5
ii = 2
ii = 4

```

---

_[View the full topic](https://discourse.julialang.org/t/optionally-multi-threaded-for-loop/81902)._
