# Nested parallel loops with @spawn

**URL:** <https://discourse.julialang.org/t/nested-parallel-loops-with-spawn/32364>\
**Category:** Numerics\
**Tags:** parallel\
**Created:** [December 17, 2019, 12:49am UTC](https://discourse.julialang.org/t/nested-parallel-loops-with-spawn/32364 "2019-12-17T00:49:40Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![tkf](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tkf/32/17635_2.png) [@tkf](https://discourse.julialang.org/u/tkf)\
**Post date:** [December 17, 2019, 3:39am UTC](https://discourse.julialang.org/t/nested-parallel-loops-with-spawn/32364/2 "2019-12-17T03:39:55Z")

</div>

I think `solve_model_spawn2!` is fast because it does not wait until the inner tasks are finished. See:

```julia
julia> t1 = Threads.@spawn begin
           global t2
           t2 = Threads.@spawn begin
               sleep(1.0)
               println("DONE")
           end
       end
       wait(t1) # this does not wait t2
       t2
Task (runnable) @0x00007f0eaff61ae0

julia> wait(t2)
DONE

```

As you can see, using raw-`@spawn` directly is pretty dangerous, since it does not do [structured concurrency](https://github.com/JuliaLang/julia/issues/33248). Using `@threads` is OK but I think using map/filter/reduce framework for multithreading is a better option (e.g., [KissThreading.jl](https://github.com/mohamed82008/KissThreading.jl), [Transducers.jl (that’s my library)](https://discourse.julialang.org/t/thread-and-process-based-parallelisms-in-transducers-jl-some-news/32285)).

---

_[View the full topic](https://discourse.julialang.org/t/nested-parallel-loops-with-spawn/32364)._
