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}:

julia> n = 1

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

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

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.


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")


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:


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

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)

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.