我是Julia的新手,正在尝试完成一个非常简单的任务:
我的代码是:
using Distributed
function f()
x=10*x
println(x)
end
@everywhere x=1
remote_do(f,2)
它不打印任何内容。另一种尝试用remotecall的方法:
r=remotecall(x->10*x,2,x)
fetch(r)
println(x)
按预期打印10(匿名函数返回什么)和1(进程1中的x)。据我了解remotecall
返回future,结果为lambda x-> 10x,但不会更改远程变量。实际上,它甚至不乘以远程变量,而是在进程1中乘以x!
问题:如何在过程1中更改和读取远程变量?
首先,x
在本地范围内为f()
,因此即使在本地进程上运行f()
也会产生错误:
julia> f()
ERROR: UndefVarError: x not defined
如果您真的想在此处使用全局变量,则需要告诉Julia:
function f()
global x=10*x
println(x)
end
julia> f()
10
然后,查看为什么它不在远程运行,您可以尝试remotecall_fetch
同步进行呼叫并查看任何异常(没有此异常,请在远程工作线程上转到stderr
。
julia> remotecall_fetch(f, 2)
ERROR: On worker 2:
UndefVarError: #f not defined
远程工作者没有f
的定义。
@everywhere function f()
global x=10*x
println(x)
end
julia> remote_do(f,2)
julia> From worker 2: 10
为了在拥有更多代码时更加轻松,可以将代码放在模块中,然后调用@everywhere using MyModule
。