使用 Distributed 实现并行计算遇到问题


#1

我准备使用 Distributed 来实现并行计算,但是遇到了以下问题,搜索很久,没有找到完美的解决方案。

首先我定义了一个模块,里面定义了一个简单的函数:

module MyModule

export f

function f(x)
  100*x
end

end

然后定义了一个包含并行计算的模块:

module ParallelTest

using Distributed
@everywhere include("MyModule.jl")


export fun
function fun(x)
    value = @distributed (+) for i = 1:round(x)
        MyModule.f(i)
    end
    return value
end

end

接下来使用脚本完成模块调用和计算,脚本保存为 testParallel.jl

using Distributed
@everywhere include("ParallelTest.jl")

value = ParallelTest.fun(2000)

println(value)

使用命令行运行

julia -p 2 testParallel.jl

发现报错如下:

WARNING: replacing module MyModule.
WARNING: replacing module MyModule.
ERROR: LoadError: On worker 2:
UndefVarError: MyModule not defined
macro expansion at E:\Work\Julia\src\testParallel\ParallelTest.jl:10 [inlined]
#1 at C:\cygwin\home\Administrator\buildbot\worker\package_win64\build\usr\share\julia\stdlib\v1.0\Distributed\src\macros.jl:276
#112 at C:\cygwin\home\Administrator\buildbot\worker\package_win64\build\usr\share\julia\stdlib\v1.0\Distributed\src\process_messages.jl:269
run_work_thunk at C:\cygwin\home\Administrator\buildbot\worker\package_win64\build\usr\share\julia\stdlib\v1.0\Distributed\src\process_messages.jl:56
macro expansion at C:\cygwin\home\Administrator\buildbot\worker\package_win64\build\usr\share\julia\stdlib\v1.0\Distributed\src\process_messages.jl:269 [inlined]
#111 at .\task.jl:259
Stacktrace:
[1] try_yieldto(::typeof(Base.ensure_rescheduled), ::Base.RefValue{Task}) at .\event.jl:196
[2] wait() at .\event.jl:255
[3] wait(::Condition) at .\event.jl:46
[4] wait(::Task) at .\task.jl:188
[5] fetch at .\task.jl:202 [inlined]
[6] iterate at .\generator.jl:47 [inlined]
[7] collect(::Base.Generator{Array{Task,1},typeof(fetch)}) at .\array.jl:619
[8] preduce(::Function, ::Function, ::UnitRange{Int64}) at C:\cygwin\home\Administrator\buildbot\worker\package_win64\build\usr\share\julia\stdlib\v1.0\Distributed\src\macros.jl:263
[9] fun(::Int64) at E:\Work\Julia\src\testParallel\ParallelTest.jl:9
[10] top-level scope at none:0
[11] include at .\boot.jl:317 [inlined]
[12] include_relative(::Module, ::String) at .\loading.jl:1044
[13] include(::Module, ::String) at .\sysimg.jl:29
[14] exec_options(::Base.JLOptions) at .\client.jl:266
[15] _start() at .\client.jl:425
in expression starting at E:\Work\Julia\src\testParallel\testParallel.jl:5

请问我该如何修改代码呢?


#2

删除此处的@everywhere 即可。


#3

谢谢,问题已解决。