Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

@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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading