# UndefVarError when initializing variable inside function with @everywhere

**URL:** <https://discourse.julialang.org/t/undefvarerror-when-initializing-variable-inside-function-with-everywhere/25183>\
**Category:** Julia at Scale\
**Created:** [June 12, 2019, 11:46am UTC](https://discourse.julialang.org/t/undefvarerror-when-initializing-variable-inside-function-with-everywhere/25183 "2019-06-12T11:46:54Z")\
**Posts on this page:** 1\
**Showing post:** 8

<div class="post-metadata">

**Author:** ![tanhevg](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tanhevg/32/12025_2.png) [@tanhevg](https://discourse.julialang.org/u/tanhevg)\
**Post date:** [June 12, 2019, 11:44pm UTC](https://discourse.julialang.org/t/undefvarerror-when-initializing-variable-inside-function-with-everywhere/25183/8 "2019-06-12T23:44:56Z")

</div>

Note that `@everywhere` executes the statement under module `Main` on the child process; this is causing the error when you move the code to module `run_h`. More on this [here](https://docs.julialang.org/en/v1/stdlib/Distributed/#Distributed.@everywhere) and [here](https://docs.julialang.org/en/v1/manual/parallel-computing/#Code-Availability-and-Loading-Packages-1).

In general, it is better to keep the functions self sufficient, and not have them rely on a global variable that is initialised from elsewhere. If you really insist on having a module-scoped global matrix `A` (which I am not at all sure you need, btw), it can be initialised lazily. Smth. like this:

```julia
# my_mod.jl
module MyMod

using Distributed, LinearAlgebra, Random

A = zeros(0,0)

function h!(x)
    global A
    if length(A) == 0
        A = zeros(100, 100)
    end

    return eigvals(rand!(MersenneTwister(x), A))

end

function run_h(iter)
    if nprocs() > 1
        @everywhere include("my_mod.jl") # See more details below
    end
    return pmap(MyMod.h!, iter) 
end

export run_h

end

```

And then in REPL:

```julia
julia> include("my_mod.jl")

julia> using .MyMod, Distributed

julia> run_h(1:20) # works

julia> addprocs(4)

julia> run_h(1:20) # also works

```

See also [this SO post](https://stackoverflow.com/questions/47685536/how-do-you-load-a-module-everywhere-inside-a-function-in-julia) on how to load the code on the workers with `@everywhere using ...`, if your module code is distributed via the package manager (apparently you need to mess with macros to achieve that). As per [addprocs doc](https://docs.julialang.org/en/v1/stdlib/Distributed/#Distributed.addprocs), the workers inherit the working directory and julia binary of the master process, unless explicitly specified otherwise. JULIA\_PROJECT is specified via the shell environment.

Hope this helps.

---

_[View the full topic](https://discourse.julialang.org/t/undefvarerror-when-initializing-variable-inside-function-with-everywhere/25183)._
