在Julia中的函数内使用addprocs()和pmap()

时间:2016-06-30 20:35:05

标签: 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广播给它们。

1 个答案:

答案 0 :(得分:1)

在您的函数中使用@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包,因为自上次使用它以来它已被更新。当我在重新编译后第一次尝试上面的脚本时,它失败了。但是,然后我退出朱莉娅并重新打开它,它工作正常。也许这就是造成你错误的原因?