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

Parallel processing 在Julia中的函数内使用addprocs()和pmap(),parallel-processing,julia,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, ad

在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
,如果用户使用
par=true
调用
f
,则会执行上面所示的操作。因此,在
f
的定义(以及模块
test
的定义)中,我想创建工人并向他们广播分发包和函数
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)

注意:当我第一次运行它时,我需要重新编译
发行版
包,因为自从我上次使用它以来,它已经被更新了。当我在重新编译之后第一次尝试上面的脚本时,它失败了。但是,后来我离开了朱莉娅,重新打开了它,它工作得很好。也许这就是导致错误的原因?

我认为问题在于
f
是在模块中定义的。如果我在REPL中执行您发布的代码,那么它确实有效。但是在模块内部定义
f
,然后调用
f
是不起作用的。我会更新这个问题。