# Optionally multi threaded for loop

**URL:** <https://discourse.julialang.org/t/optionally-multi-threaded-for-loop/81902>\
**Category:** Performance\
**Tags:** question\
**Created:** [May 30, 2022, 7:51am UTC](https://discourse.julialang.org/t/optionally-multi-threaded-for-loop/81902 "2022-05-30T07:51:19Z")\
**Posts on this page:** 1\
**Showing post:** 7

<div class="post-metadata">

**Author:** ![Benny](https://avatars.discourse-cdn.com/v4/letter/b/49beb7/32.png) [@Benny](https://discourse.julialang.org/u/Benny)\
**Post date:** [May 30, 2022, 5:56pm UTC](https://discourse.julialang.org/t/optionally-multi-threaded-for-loop/81902/7 "2022-05-30T17:56:51Z")

</div>

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:

```julia
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.

---

_[View the full topic](https://discourse.julialang.org/t/optionally-multi-threaded-for-loop/81902)._
