Multithreading simultaneously in two functions

Is there a way to do use all 9 threads in the following functions?

function f1()
    Threads.@threads for i in 1:3
        println("MCMC")
        println("$(Threads.threadid())")
        sleep(3.0)
    end
    println("#############")
end

function f2()
    Threads.@threads for i in 1:3
        println("Model")
        f1()
        println("$(Threads.threadid())")
    end
end

Right now running this prints the following:

$ julia -t 9

> f2()

Model
Model
Model
MCMC
2
MCMC
1
MCMC
3
MCMC
3
MCMC
1
MCMC
2
MCMC
MCMC
MCMC
2
3
1
#############
#############
2
1
#############
3
julia> function f1()
           @sync for i in 1:3
               Threads.@spawn begin
                   println("MCMC")
                   println("$(Threads.threadid())")
                   sleep(3.0)
                   end
               end
           println("#############")
       end

julia> function f2()
          @sync for i in 1:3
               println("Model")
               Threads.@spawn f1()
               println("$(Threads.threadid())")
           end
       end

julia> f2()
Model
1
Model
1
Model
1
MCMC
MCMC
MCMC
5
MCMC
MCMC
MCMC
3
2
MCMC
4
8
7
5
MCMC
7
MCMC
7
#############
#############
#############

something like this

1 Like

Thank you for the solution.

Can you briefly explain what’s happening in your code?