# Toggle Threads.@threads with a variable

**URL:** https://discourse.julialang.org/t/toggle-threads-threads-with-a-variable/71818
**Category:** General Usage
**Created:** [November 20, 2021, 9:24am UTC](https://discourse.julialang.org/t/toggle-threads-threads-with-a-variable/71818 "2021-11-20T09:24:39Z")
**Posts on this page:** 1
**Showing post:** 3

<div class="post-metadata">

### Author: ![carstenbauer](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/carstenbauer/32/4981_2.png) [@carstenbauer](https://discourse.julialang.org/u/carstenbauer)
#### Post date: [November 20, 2021, 1:53pm UTC](https://discourse.julialang.org/t/toggle-threads-threads-with-a-variable/71818/3 "2021-11-20T13:53:26Z")

</div>

I sometime use a clever pattern which has been originally suggested [here](https://discourse.julialang.org/t/assert-alternatives/24775/14):

```julia
module MyModule

using Base.Threads

use_threads() = true

macro maybe_threads(code)
    return esc(:(
        if $(@ __MODULE__ ).use_threads()
            @threads($code)
        else
            $code
        end
    ))
end

function computation()
    @maybe_threads for i in 1:10
        @show i, threadid()
    end
end

end

```

which gives

```julia
julia> MyModule.computation()
(i, threadid()) = (3, 2)
(i, threadid()) = (4, 2)
(i, threadid()) = (1, 1)
(i, threadid()) = (2, 1)
(i, threadid()) = (10, 6)
(i, threadid()) = (7, 4)
(i, threadid()) = (8, 4)
(i, threadid()) = (9, 5)
(i, threadid()) = (5, 3)
(i, threadid()) = (6, 3)

julia> MyModule.use_threads() = false

julia> MyModule.computation()
(i, threadid()) = (1, 1)
(i, threadid()) = (2, 1)
(i, threadid()) = (3, 1)
(i, threadid()) = (4, 1)
(i, threadid()) = (5, 1)
(i, threadid()) = (6, 1)
(i, threadid()) = (7, 1)
(i, threadid()) = (8, 1)
(i, threadid()) = (9, 1)
(i, threadid()) = (10, 1)

julia> MyModule.use_threads() = true

julia> MyModule.computation()
(i, threadid()) = (5, 3)
(i, threadid()) = (9, 5)
(i, threadid()) = (3, 2)
(i, threadid()) = (4, 2)
(i, threadid()) = (10, 6)
(i, threadid()) = (6, 3)
(i, threadid()) = (1, 1)
(i, threadid()) = (2, 1)
(i, threadid()) = (7, 4)
(i, threadid()) = (8, 4)

```

---

_[View the full topic](https://discourse.julialang.org/t/toggle-threads-threads-with-a-variable/71818)._
