# Repeated multithreaded region

**URL:** <https://discourse.julialang.org/t/repeated-multithreaded-region/75037>\
**Category:** Performance\
**Tags:** question, multithreading\
**Created:** [January 22, 2022, 3:37pm UTC](https://discourse.julialang.org/t/repeated-multithreaded-region/75037 "2022-01-22T15:37:47Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![bjack205](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/bjack205/32/7294_2.png) [@bjack205](https://discourse.julialang.org/u/bjack205)\
**Post date:** [January 22, 2022, 3:37pm UTC](https://discourse.julialang.org/t/repeated-multithreaded-region/75037/1 "2022-01-22T15:37:47Z")

</div>

I’m wondering what the best way to repeatedly call a parallelized piece of code in a serial loop? For example, in smooth nonlinear optimization, we often need to calculate an expansion of objective and constraints about the current iterate, which often can be done in parallel, e.g.

```julia
for iter = 1:max_iters
    @threads for i = 1:nwork
        dowork(i)
    end
    computestep()
    updateiterate()
end

```

How do we avoid the overhead of setting up threads each time through the loop? In a paradigm such as OpenMP, you’d set up the threads once, split the work among works for the parallel section, and assign the serial portion to the main thread, with the other threads idling. What’s the “right” way to do this in Julia? Is `@spawn` a better option here? The few times I’ve tried doing stuff like this the overhead of calling `@threads` has made it much slower than a serial version of the code.

---

<div class="post-metadata">

**Author:** ![lawless-m](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/lawless-m/32/30869_2.png) [@lawless-m](https://discourse.julialang.org/u/lawless-m)\
**Post date:** [January 22, 2022, 3:44pm UTC](https://discourse.julialang.org/t/repeated-multithreaded-region/75037/2 "2022-01-22T15:44:45Z")

</div>

Without knowing a better way to create a threadpool, I would spawn a bunch of channels and have them `take` as a “do-work-now” token

---

<div class="post-metadata">

**Author:** ![carstenbauer](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/carstenbauer/32/4981_2.png) [@carstenbauer](https://discourse.julialang.org/u/carstenbauer)\
**Post date:** [January 22, 2022, 4:13pm UTC](https://discourse.julialang.org/t/repeated-multithreaded-region/75037/3 "2022-01-22T16:13:28Z")

</div>

You might want to try `@batch` from [Polyester.jl](https://github.com/JuliaSIMD/Polyester.jl) (as a direct replacement for `@threads`) . It should have lower overhead because (AFAIU) it “reuses” threads more efficiently.
