Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run two functions simultaneously in julia?

I'm trying to run two functions simultaneously in julia, but I don't know how to do it. Here you can see my code:

function area(side::Float64)
    return side*side
end

function f(n::Int64)
    mat = zeros(n,n)
    for i=1:n
        for j=1:n
            mat[i,j] = area(rand())
        end
    end
    return mat
end

function g(n::Int64)
    mat = zeros(n,n)
    for i=1:n
        for j=1:n
            mat[i,j] = area(rand()*rand())
        end
    end
    return mat
end

s1 = f(10)
s2 = g(10)
hcat(s1,s2)
like image 727
bitWise Avatar asked Jan 31 '26 04:01

bitWise


1 Answers

In Julia 1.3 you can spawn tasks that will get scheduled on different threads using Threads.@spawn:

begin
s1 = Threads.@spawn f(10)
s2 = Threads.@spawn g(10)
s1 = fetch(s1)
s2 = fetch(s2)
end

See the announcement blog post for more info: https://julialang.org/blog/2019/07/multithreading.

like image 182
Kristoffer Carlsson Avatar answered Feb 01 '26 21:02

Kristoffer Carlsson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!