Atsushi Sakai
Atsushi Sakai

Reputation: 1004

How to use @everywhere macro in a simple Julia code for parallel computing

I am trying to write a simple Julia code for parallel computing.

I wrote a simple code based on this doc: https://docs.julialang.org/en/latest/manual/parallel-computing

@everywhere function test(x)
    return x * 2.0
end

nprocess = 5
addprocs(nprocess)
responses = Vector{Any}(nworkers())

for i in 1:nworkers()
    responses[i] = remotecall(test, i+1, i)
end

for res in responses
    wait(res)
end

However, I got this error message.

ERROR: LoadError: On worker 2:

UndefVarError: #test not defined

I think the @everywhere macro doesn't work correctly.

I'm using Julia 0.6.0.

Does anyone know how to fix it?

Upvotes: 6

Views: 3027

Answers (1)

Dan Getz
Dan Getz

Reputation: 18217

The @everywhere and the addprocs are in the reverse order (causing the added workers not to know about the function test). The other way around it works and doesn't do the UndefVarError:

nprocess = 5
addprocs(nprocess)
responses = Vector{Any}(nworkers())

@everywhere function test(x)
    return x * 2.0
end

for i in 1:nworkers()
    responses[i] = remotecall(test, i+1, i)
end

for res in responses
    wait(res)
end

Upvotes: 6

Related Questions