2

I just encountered a very confusing julia behavior. I always thought that variables defined inside a function remain local to that function. But in the following example, the scope changes.

I define a simple function as below

using Distributed
addprocs(2)

function f()
    @everywhere x = myid()
    @everywhere println("x = ", x)
end

Executing the following code

f()

gives the result

x = 1
From worker 2:    x = 2
From worker 3:    x = 3

But since x is defined inside the function, I would expect the variable x to be not defined outside the function. However, upon executing the following code

x

I get the result

1

Even more confusing is the execution of the following code

@fetchfrom 3 x

which again gives

1

This is super confusing behavior. First, how does x become available outside the function? Second, why are all the processors/cores returning the same value of x? Thank you for your help.

singularity
  • 335
  • 1
  • 7
  • 1
    `@everywhere` always evaluates into `Main` on the process on which it's executed. `@fetchfrom` doesn't work as you expect I think - check [this](https://stackoverflow.com/questions/27677399/julia-how-to-copy-data-to-another-processor-in-julia?noredirect=1&lq=1) discussion which gives the functions you want. `fetch(@spawnat(3, getfield(Main, :x)))` returns 3 as expected. – Nils Gudat Mar 05 '22 at 09:06

0 Answers0