parallel-processing - 在 Julia 的函数中使用 addprocs() 和 pmap()

标签 parallel-processing julia

在 Julia 中,我想使用 addprocspmap在模块内部定义的函数内部。这是一个愚蠢的例子:

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/

相关文章:

java - 执行线程核心数

julia - 使用 HTTP.jl 的异步 GET 请求的参数

julia - 重新加载模块/文件和任务问题

methods - 如何在 Julia 中指定函数的类型/签名?

Julia :重新解释的反面(相反)是什么?

bash - 在 bash 中并行运行有限数量的子进程?

r - 无法为并行集群打开套接字

parallel-processing - OpenMDAO遗传算法不能并行运行?

python - 在 Julia 中使用 PyPlot 会出现错误 : PyCall not properly installed

c - 如何在 openmp 中并行化 while 循环 - 共轭梯度