# 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:** 4

<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, 2:23pm UTC](https://discourse.julialang.org/t/undefvarerror-when-initializing-variable-inside-function-with-everywhere/25183/4 "2019-06-12T14:23:17Z")

</div>

Just pre-allocate `A` outside of the function. The `@everywhere` macro executes just the statement that is passed to it, so `A` will be in global scope on the child processes anyway.

The code below works, regardless of whether `addprocs` were called or not.

```julia
using Distributed
addprocs(4)
@everywhere using LinearAlgebra, Random

@everywhere A = zeros(100, 100)

@everywhere function h!(x)

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

end

function run_h(iter)
    if nprocs()>1
        return pmap(x->h!(x), iter)
    else
        return map(x->h!(x), iter)
    end
end

```

---

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