5

I want to run a function on a separate core. I wrote a script that runs it asynchronously in parallel two times.

const results = Channel()


function my_function()
    delay = rand() * 5
    @info "Task with $delay s"
    @info "Thread $(Threads.threadid())"
    sleep(delay)
    put!(results, delay)
end


errormonitor(@async my_function())
errormonitor(@async my_function())


@info "returned $(take!(results))"
@info "returned $(take!(results))"

But both times in the same thread.

[ Info: Task with 2.9497522378270298 s
[ Info: Task with 4.956428193185428 s
[ Info: Thread 1
[ Info: Thread 1
[ Info: returned 2.9497522378270298
[ Info: returned 4.956428193185428

How can I run my_function on different threads?

2
  • 1
    It's a cliche thing to say, but have you read the docs? Async, threading, and multiprocessing are, in a sense, orthogonal. Or have you just forgot to start Julia with --threads? Commented Feb 9, 2022 at 13:37
  • you correctly noticed that it is difficult for me to understand these things. I ran with both the --threads 2 flag and the -p 2 flag. the answer was the same. Commented Feb 9, 2022 at 13:53

1 Answer 1

9

@async tasks run on the thread that scheduled them (thread 1 in your example). To spawn a task on a thread, use Threads.@spawn (and make sure to start Julia with more than one thread):

$ cat main.jl 
const results = Channel()

function my_function()
    delay = rand() * 5
    @info "Task with $delay s running on thread $(Threads.threadid())"
    sleep(delay)
    put!(results, delay)
end

Threads.@spawn my_function()
Threads.@spawn my_function()

@info "returned $(take!(results))"
@info "returned $(take!(results))"

$ julia --threads=auto main.jl
[ Info: Task with 0.3894362661856865 s running on thread 2
[ Info: Task with 1.4960360211694967 s running on thread 4
[ Info: returned 0.3894362661856865
[ Info: returned 1.4960360211694967

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.