Alexander Rakhmaev
Alexander Rakhmaev

Reputation: 1055

How to run a function on a separate thread in Julia?

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?

Upvotes: 5

Views: 1150

Answers (1)

fredrikekre
fredrikekre

Reputation: 10984

@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

Upvotes: 9

Related Questions