Putting Threads.@threads or any macro in an if statement

Macros are expanded at parse-time, not runtime, so the macro needs to figure out what code to write way before multithreaded ever receives a value. However, you can make your macro expand to have a branch in it like so:

macro usethreads(multithreaded, expr::Expr)
    ex = quote
        if $multithreaded
            Threads.@threads $expr
        else
            $expr
        end
    end
    esc(ex)
end

If you have both this definition and this one:

macro usethreads(multithreaded::Bool, expr::Expr)
    if multithreaded
        return esc(:(Threads.@threads $expr))
    else
        return esc(:($expr))
    end
end

then it’ll use the ::Bool definition if you literally write true or false and the other definition otherwise.

7 Likes