Threads.@spawn not using master thread

I’ve been using Julia to parallelize some algorithms, so I’m also studying how julia parallel programming works.
I did a simple code to check the behavior of Threads.@spawn and I’ve noticed it would only use the master thread the first time I called the function with the macro, if I kept calling it, it would not use the master thread anymore.
Could someone explain this behavior to me?

This is the code I used is this one. The call_threads is the array I count how many times the thread is invoked, I noticed it stores a value the first time I call the function, but the value that corresponds to the first thread doesn’t change in the following calls.

max_thread = zeros(Threads.nthreads())
call_threads = zeros(Threads.nthreads())

function generatingNumber()
    candidate = (rand() * 20)
    if (candidate > max_thread[Threads.threadid()])
        max_thread[Threads.threadid()] = candidate
    call_threads[Threads.threadid()] +=1

function runthreads()
    global max_thread
    thread = Task[]
    for i in 1:100
        push!(thread, Threads.@spawn generatingNumber())
    for i in 1:length(thread)
    max_value = maximum(max_thread)
    max_thread = zeros(Threads.nthreads())
1 Like

Since your task workload is trivial, it takes longer to allocate and schedule the task than to execute it. So by the time the master thread exits the push loop, most or all of the work has been done by the others. @spawn takes hundreds of cycles, whereas rand() seems to average around 20.

Indeed, I added a sleep in the generatingNumber function and it kept spawning at master thread. I still don’t understand why before that it would spawn at first thread only at first call.