Toggle Threads.@threads with a variable

I sometime use a clever pattern which has been originally suggested here:

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