在 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)
这会返回一个很长的错误
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()
我要做的是编写一个包,其中包含执行操作的函数,这些操作可以由用户自行决定并行化。所以像
f
这样的函数可能需要一个参数par::Bool
如果用户调用 f
,它会执行我上面显示的操作与 par = true
否则循环。所以在 f
的定义中(并且在模块 test
的定义内),我想创建工作人员并广播 Distributions 包和函数 g
给他们。
最佳答案
使用 @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)
注意:当我第一次运行它时,我需要重新编译
Distributions
自从我上次使用它以来它已经更新了。当我在重新编译后第一次尝试上述脚本时,它失败了。但是,然后我退出 Julia 并重新打开它,它运行良好。也许这就是导致您的错误的原因?
关于parallel-processing - 在 Julia 的函数中使用 addprocs() 和 pmap(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38132780/