Parallel execution of a number of lines

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:

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.

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!

You can use @spawn instead:

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
1 Like
1 Like