Optionally multi threaded for loop

Your concern about code duplication is valid, but there’s a bit of nuance here. Single-threaded and multi-threaded loops work very differently, so the code has to be different on some level. @threads is easy to type in front of a loop, but it’s doing a lot to the loop’s code at parse-time, just dig into its source code and see. The source code however remains the same to you, and you maintain it the same way as if it weren’t multithreaded.

Similarly, you could accomplish @skleinbo did with foo(mt) but by applying a macro to a loop, looking something like:

function foo(multi_thread=true)
  @multi_single_branch for ii in 1:10
    @show ii
  end
end

This way, you can have your branched code at parse-time but don’t need to maintain duplicated code in the source.
You are probably right about eschewing multimethods; besides there being little gain, it seems like it’ll need a more complicated macro than making a loop.

2 Likes