# Parallel execution of a number of lines

**URL:** <https://discourse.julialang.org/t/parallel-execution-of-a-number-of-lines/89765>\
**Category:** General Usage\
**Tags:** parallel, multithreading, threads\
**Created:** [November 4, 2022, 9:08am UTC](https://discourse.julialang.org/t/parallel-execution-of-a-number-of-lines/89765 "2022-11-04T09:08:50Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![CeterisPartybus](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/ceterispartybus/32/46868_2.png) [@CeterisPartybus](https://discourse.julialang.org/u/CeterisPartybus)\
**Post date:** [November 4, 2022, 9:08am UTC](https://discourse.julialang.org/t/parallel-execution-of-a-number-of-lines/89765/1 "2022-11-04T09:08:50Z")

</div>

Is there a way to run multiple lines of code in parallel on multiple threads? I am familiar with the @threads for loop. But I would like to tell Julia that some lines can be run in parallel instead of sequentially.  
To give an example: Assume I have two `A` and `B,` and I would like to do some completely separate operations in different lines on parallel threads instead of one after another. Here some minimum code:

```julia
A = rand(Float64, (100, 100))
B = rand(Float64, (100, 100))

# These should now be in parallel
C = inv(A)
D = inv(B)

# Wait here until all from above is finished, and then continue.

```

I could do it in a @threads for loop like this but I am not sure about performance and is a weird workaround.

```julia
A = rand(Float64, (100, 100))
B = rand(Float64, (100, 100))

# These should now be in parallel
Threads.@threads for i = 1:2
    if i == 1
        C = inv(A)
    elseif i == 2
        D = inv(B)
    end
end

```

Thanks a lot for any hint or suggestion!

---

<div class="post-metadata">

**Author:** ![jmair](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jmair/32/35117_2.png) [@jmair](https://discourse.julialang.org/u/jmair)\
**Post date:** [November 4, 2022, 9:24am UTC](https://discourse.julialang.org/t/parallel-execution-of-a-number-of-lines/89765/2 "2022-11-04T09:24:24Z")

</div>

You can use `@spawn` instead:

```julia
C_task = Threads.@spawn inv(A) # starts processing on a different thread
D = inv(B) # do second piece of work on main thread
C = fetch(C_task) # waits until spawned thread has finished

```

---

<div class="post-metadata">

**Author:** ![qwerty](https://avatars.discourse-cdn.com/v4/letter/q/4491bb/32.png) [@qwerty](https://discourse.julialang.org/u/qwerty)\
**Post date:** [November 4, 2022, 9:52am UTC](https://discourse.julialang.org/t/parallel-execution-of-a-number-of-lines/89765/3 "2022-11-04T09:52:15Z")

</div>

> **[GitHub - JuliaParallel/Dagger.jl: A framework for out-of-core and parallel...](https://github.com/JuliaParallel/Dagger.jl)**
>
> A framework for out-of-core and parallel execution - GitHub - JuliaParallel/Dagger.jl: A framework for out-of-core and parallel execution
