Joh*_*ito 5 parallel-processing julia
在 Julia 中,我想在模块内部定义的函数中使用addprocs和pmap。这是一个愚蠢的例子:
module test
using Distributions
export g, f
function g(a, b)
a + rand(Normal(0, b))
end
function f(A, b)
close = false
if length(procs()) == 1 # If there are already extra workers,
addprocs() # use them, otherwise, create your own.
close = true
end
W = pmap(x -> g(x, b), A)
if close == true
rmprocs(workers()) # Remove the workers you created.
end
return W
end
end
test.f(randn(5), 1)
Run Code Online (Sandbox Code Playgroud)
这将返回一个很长的错误
WARNING: Module test not defined on process 4
WARNING: Module test not defined on process 3
fatal error on fatal error on WARNING: Module test not defined on process 2
43: : WARNING: Module test not defined on process 5
fatal error on fatal error on 5: 2: ERROR: UndefVarError: test not defined
in deserialize at serialize.jl:504
in handle_deserialize at serialize.jl:477
in deserialize at serialize.jl:696
...
in message_handler_loop at multi.jl:878
in process_tcp_streams at multi.jl:867
in anonymous at task.jl:63
Worker 3 terminated.
Worker 2 terminated.ERROR (unhandled task failure): EOFError: read end of file
WARNING: rmprocs: process 1 not removed
Worker 5 terminated.ERROR (unhandled task failure): EOFError: read end of file
4-element Array{Any,1}:Worker 4 terminated.ERROR (unhandled task failure): EOFError: read end of file
ERROR (unhandled task failure): EOFError: read end of file
ProcessExitedException()
ProcessExitedException()
ProcessExitedException()
ProcessExitedException()
Run Code Online (Sandbox Code Playgroud)
我想要做的是编写一个包,其中包含执行可以由用户自行决定并行化的操作的函数。因此,如果用户调用with和 循环,则像这样的函数f可能会接受一个参数par::Bool,该参数会执行我上面显示的操作。因此,从(以及模块的定义)的定义中,我想创建工作人员并向他们广播分发包和功能。fpar = trueftestg
在你的函数中使用有什么问题@everywhere?例如,以下内容在我的计算机上运行良好。
function f(A, b)
close = false
if length(procs()) == 1 # If there are already extra workers,
addprocs() # use them, otherwise, create your own.
@everywhere begin
using Distributions
function g(a, b)
a + rand(Normal(0, b))
end
end
close = true
end
W = pmap(x -> g(x, b), A)
if close == true
rmprocs(workers()) # Remove the workers you created.
end
return W
end
f(randn(5), 1)
Run Code Online (Sandbox Code Playgroud)
注意:当我第一次运行这个程序时,我需要重新编译该Distributions包,因为自从我上次使用它以来它已经更新了。当我在重新编译后第一次尝试上面的脚本时,它失败了。但是,我随后退出了 Julia 并重新打开了它,效果很好。也许这就是导致您错误的原因?