你如何在 Julia 的函数中加载模块@everywhere

cak*_*ako 3 module distributed-computing julia

在使用addprocs. 当addprocs在顶层调用时,一切都很好。但是,当我将代码包装在函数中时,我无法做同样的事情。

就我而言,我正在动态添加工作人员,因此@everywhere using XXX始终在顶层调用是不可行的,我需要在函数内部执行此操作。

简而言之,这有效:

addprocs(1)
@everywhere using XXX
Run Code Online (Sandbox Code Playgroud)

而这不会:

function myaddprocs()
    addprocs(1)
    @everywhere using XXX
end
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

cak*_*ako 5

经过更多的调查,我已经查明了一些使我的代码无法正常工作的问题。

  1. 进口必须发生 addprocs. 如果之前发生过导入,则导入必须以@everywhere.

  2. using函数内的顶级表达式(例如)不起作用,除非包含在eval语句中。

对我的代码的修复是:

function myaddprocs()
    addprocs(1)
    eval(macroexpand(quote @everywhere using XXX end))
end
Run Code Online (Sandbox Code Playgroud)

例子

我已经在 J​​ulia 0.6.1 上测试了以下代码片段。我还在 SGE 集群 (OGS/GE 2011.11p1) 上使用相同版本对它们进行了测试,方法是全部替换addprocsaddprocs_sge,然后导入ClusterManagers.jl. 以下代码段有效:

  • using之后addprocs

    addprocs(1)
    using SpecialFunctions
    pmap(x->SpecialFunctions.sinint(1), workers())
    
    Run Code Online (Sandbox Code Playgroud)
  • using之前和之后addprocs,第二个是@everywhere

    using SpecialFunctions
    addprocs(1)
    @everywhere using SpecialFunctions
    pmap(x->sinint(1), workers())
    
    Run Code Online (Sandbox Code Playgroud)
  • using包裹在函数内eval之后addprocs

    function getprocs()
        addprocs(1)
        eval(Expr(:using,:SpecialFunctions))
        pmap(x->SpecialFunctions.sinint(1), workers())
    end
    getprocs()
    
    Run Code Online (Sandbox Code Playgroud)
  • 和以前一样,with@everywhere应用于eval

    function getprocs()
        addprocs(1)
        @everywhere eval(Expr(:using,:SpecialFunctions))
        pmap(x->sinint(1), workers())
    end
    getprocs()
    
    Run Code Online (Sandbox Code Playgroud)
  • 和以前一样,用@everywherewithineval代替

    function getprocs()
        addprocs(1)
        eval(macroexpand(quote @everywhere using SpecialFunctions end))
        pmap(x->sinint(1), workers())
    end
    getprocs()
    
    Run Code Online (Sandbox Code Playgroud)

另一方面,这些片段不起作用: