Optional macro invocation

version 2 of my maybethread macro above, which optionally threads at compile time, is now hygienic:

macro maybethread(loop)
  if use_threads
    quote Threads.@threads $(Expr(loop.head,
                             Expr(loop.args[1].head, esc.(loop.args[1].args)...),
                             esc(loop.args[2]))); end
  else
    # @warn "running single threaded"
    quote $(esc(loop)); end
  end
end

i typically define use_threads = Threads.nthreads()>1.

thanks @chakravala for your post which showed me how to do this.

figuring this out took a long time. maybe i’m stupid. maybe macros are hard. but i wholeheartedly agree with @c42f that we should rethink them for julia 2.0.

2 Likes