在远程过程中更改/访问远程变量

问题描述 投票:0回答:1

我是Julia的新手,正在尝试完成一个非常简单的任务:

  1. 将变量x = 1分配给每个进程
  2. 仅在进程2中将x更改为其他值(将x本地更改为进程2)
  3. 在过程2中打印远程x的新值

我的代码是:

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中更改和读取远程变量?

julia distributed-computing
1个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.