Return values with @async

Hi everyone,

I would like to run two functions at the same time. A very basic example is

addprocs(3)

@everywhere begin
    function f()
        sleep(1)
        println("function f() is working")
        return [1 2]
    end

    function g()
        sleep(2)
        println("function g() is working")
        return [3 4 5]
    end
end

Then, I can perfect run them using remotecall_fetch

a,b = 0,0
@time begin
    a = remotecall_fetch(f,2)
    b = remotecall_fetch(g,3)
end
println(a)
println(b)

The result is:

        From worker 2:	function f() is working
	From worker 3:	function g() is working
  3.005970 seconds (957 allocations: 51.297 KiB)
[1 2]
[3 4 5]

I would like to use @async, but the end result is wrong:

a,b = 0,0
@time @sync begin
    @async a = remotecall_fetch(f,2)
    @async b = remotecall_fetch(g,3)
end
println(a)
println(b)
        From worker 2:	function f() is working
	From worker 3:	function g() is working
  2.031729 seconds (1.40 k allocations: 88.197 KiB)
0
0

what am I missing ?

I think there’s a local scope in there somewhere.

Try using global:

@time @sync begin
    @async global a = remotecall_fetch(f,2)
    @async global b = remotecall_fetch(g,3)
end

But you probably want to return a, b from a function.

Only for reference. Using @spawn does the job

a,b = 0,0
@time begin
    a = @spawn f()
    b = @spawn g()
    a,b = fetch(a), fetch(b)
end
println(a)
println(b)
    From worker 4:  function f() is working
    From worker 2:  function g() is working
  2.029705 seconds (2.91 k allocations: 183.444 KiB)
[1 2]
[4 5 6]