I try to keep some computation results in each workers and fetch them together after all computation is done. However, I could not actually modify the variable of the workers.
Here is a simplified example
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
This sample tries to modify x contained in each worker. I expect x to be like 5, but the final fetch gives the initial value 0
By running
fetch(@spawnat 2 x)you unintentionally transferred the value ofxfrom the current worker to worker 2.See this example:
If you want to retrieve the value of
x, you could try the following:See https://docs.julialang.org/en/v1/manual/distributed-computing/#Global-variables