Optionally multi threaded for loop

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
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:

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> 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
8 Likes