How to run two functions simultaneously in julia?

Viewed 535

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)
2 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.

Generally, there are different notions of "simultaneous" in parallel computing.

Since you tagged your question as "multiprocessing" let me give you a straightforward multi process solution (which should work for any Julia version >= 0.7). As such, it utilizes Julias built-in Distributed computing tools.

using Distributed
nworkers() < 2 && addprocs(2) # add two worker processes if necessary

@everywhere begin # define your functions on both workers
    area(side::Float64) = side*side

    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
end

# spawn tasks on the two workers (non-blocking)
t1 = @spawn f(10)
t2 = @spawn g(10)

# fetch the results (blocking until workers have finished)
r1 = fetch(t1)
r2 = fetch(t2)
hcat(r1,r2)

For more on how to use Distributed for parallel computing checkout, for example, this part of the Julia documentation or this Jupyter workshop from one of my workshops: Parallel Computing in Julia.

Related