Julia Distributed,修改worker的全局变量失败

Julia Distributed, failed to modify the global variable of the worker

我尝试在每个worker中保留一些计算结果,并在所有计算完成后将它们一起取出。但是,我实际上无法修改工人的变量。

这是一个简化的例子

using Distributed
addprocs(2)

@everywhere function modify_x()
    global x
    x += 1
    println(x)  # x will increase as expected
end  

@everywhere x = 0

@sync @distributed for i in 1:10
    modify_x()
end

fetch(@spawnat 2 x) # gives 0

此示例尝试修改每个工作程序中包含的 x。我希望 x5,但最后的 fetch 给出初始值 0

通过 运行 fetch(@spawnat 2 x) 你无意中将 x 的值从当前 worker 转移到了 worker 2.

看这个例子:

julia> x = 3
3

julia> fetch(@spawnat 2 x)
3

如果您想检索 x 的值,您可以尝试以下操作:

julia> @everywhere x = 0

julia> @sync @distributed for i in 1:10
           modify_x()
       end
      From worker 3:    1
      From worker 3:    2
      From worker 3:    3
      From worker 3:    4
      From worker 3:    5
      From worker 2:    1
      From worker 2:    2
      From worker 2:    3
      From worker 2:    4
Task (done) @0x000000000d34a6d0      From worker 2:     5


julia> @everywhere function fetch_x()
           return x
       end

julia> fetch(@spawnat 2 fetch_x())
5

https://docs.julialang.org/en/v1/manual/distributed-computing/#Global-variables