I am new to Julia and trying to do a very simple task:
My code is:
using Distributed
function f()
x=10*x
println(x)
end
@everywhere x=1
remote_do(f,2)
It does not print anything. Another try with remotecall:
r=remotecall(x->10*x,2,x)
fetch(r)
println(x)
prints 10 (what anonymous function returns) and 1 (x in process 1) as expected.
As I understand remotecall
returns a future with result of lambda x->10x but does not change the remote variable. In fact it even does not multiply the remote variable but x in process 1!
Question: How to change and read remote variable in process 1?
First, x
is scoped locally to f()
, so even running f()
on the local process produces an error:
julia> f()
ERROR: UndefVarError: x not defined
If you really want to use a global variable here, you need to tell Julia that:
function f()
global x=10*x
println(x)
end
julia> f()
10
Then, to see why it isn't running remotely, you can try remotecall_fetch
to make the call synchronously and see any exceptions (without this exceptions go to stderr
on the remote worker).
julia> remotecall_fetch(f, 2)
ERROR: On worker 2:
UndefVarError: #f not defined
The remote worker does not have a definition for f
.
@everywhere function f()
global x=10*x
println(x)
end
julia> remote_do(f,2)
julia> From worker 2: 10
To make this easier when you have more code, you could place the code in a module and then call @everywhere using MyModule
.