Modify a remote object

Hello, I would like to send an object to a worker and modify the remote object. The following code did not work as expected.

julia> addprocs(1)
1-element Array{Int64,1}:
 2

julia> n = 1
1

julia> remotecall_fetch(()->n, 2)
1

julia> @everywhere function add1(n)
        n += 1
        println("n = $n")
       end

julia> remotecall_fetch(add1,2,n)
	From worker 2:	n = 2

julia> remotecall_fetch(add1,2,n)
	From worker 2:	n = 2              # expected 3

julia> remotecall_fetch(add1,2,n)
	From worker 2:	n = 2            # expected 4

I was expecting the value of n to have increased in the worker.

Thanks!

n is local (a parameter) to function add1, so global n will not be incremented (even if executed locally).

Not sure what you want, but this will increment global n:

@everywhere function add2()
    global n
    n += 1
    println("n = $n")
end

remotecall_fetch(add2,2)

Hi, thanks for the quick response

I want to move an object to another worker and modify it in place iteratively. In your example, is global n the variable in worker 1 or worker 2?. In other words, I would like the function to take the variable Main2.n and modify it, where Main2 is the Main module in worker 2.

worker 2.

Maybe something like:

addprocs(1)

@everywhere begin
    defineA(src) = global const A = src
    incrementA() = (A .+= 1)
    getA() = A
end

Test it out:

p = 2
B = zeros(Int,2,2)
remotecall_fetch(defineA, p, B)
remotecall_fetch(getA, p)
remotecall_fetch(incrementA, p)
remotecall_fetch(getA, p)
B

.
You might also want to look at: How to avoid repeated data movement between processes?

See also ParallelDataTransfer, which provides helper functions for transferring data between worker processes.