Confusing julia behavior. @everywhere macro changes the scope of local variables to global

Viewed 94

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.

0 Answers
Related