【问题标题】:Shared array usage in JuliaJulia 中的共享数组使用
【发布时间】:2016-03-02 15:27:24
【问题描述】:

我需要在多个工作人员上并行执行某个任务。 为此,我需要所有工作人员都可以访问存储数据的矩阵。

我认为数据矩阵可以实现为共享数组,以最大限度地减少数据移动。

为了让我开始使用共享数组,我正在尝试以下非常简单的示例,它给了我,我认为是意外的行为:

julia -p 2

# the data matrix
D = SharedArray(Float64, 2, 3)

# initialise the data matrix with dummy values
for ii=1:length(D)
   D[ii] = rand()
end

# Define some kind of dummy computation involving the shared array 
f = x -> x + sum(D)

# call function on worker
@time fetch(@spawnat 2 f(1.0))

最后一个命令给了我以下错误:

 ERROR: On worker 2:
 UndefVarError: D not defined
 in anonymous at none:1
 in anonymous at multi.jl:1358
 in anonymous at multi.jl:904
 in run_work_thunk at multi.jl:645
 in run_work_thunk at multi.jl:654
 in anonymous at task.jl:58
 in remotecall_fetch at multi.jl:731
 in call_on_owner at multi.jl:777
 in fetch at multi.jl:795

我认为共享数组 D 应该对所有工作人员可见? 我显然缺少一些基本的东西。提前致谢。

【问题讨论】:

    标签: arrays parallel-processing julia


    【解决方案1】:

    虽然底层数据是共享给所有工人的,D 的声明却不是。你仍然需要传递对 D 的引用,所以像

    f = (x,SA) -> x + sum(SA) @time fetch(@spawnat 2 f(1.0,D))

    应该可以。您可以在主进程上更改 D 并查看它实际上使用的是相同的数据:

    julia> # call function on worker
           @time fetch(@spawnat 2 f(1.0,D))
      0.325254 seconds (225.62 k allocations: 9.701 MB, 5.88% gc time)
    4.405613684678047
    
    julia> D[1] += 1
    1.2005544517241717
    
    julia> # call function on worker
           @time fetch(@spawnat 2 f(1.0,D))
      0.004548 seconds (637 allocations: 45.490 KB)
    5.405613684678047
    

    【讨论】:

    • 您对分享声明的解释非常有帮助。谢谢。
    【解决方案2】:

    这工作,没有通过函数内的闭包声明 D。

    function dothis()
        D = SharedArray{Float64}(2, 3)
    
        # initialise the data matrix with dummy values
        for ii=1:length(D)
           D[ii] = ii #not rand() anymore
        end
    
        # Define some kind of dummy computation involving the shared array 
        f = x -> x + sum(D)
    
        # call function on worker
        @time fetch(@spawnat 2 f(1.0))
    end
    
    julia> dothis()
    1.507047 seconds (206.04 k allocations: 11.071 MiB, 0.72% gc time)
    22.0
    julia> dothis()
    0.012596 seconds (363 allocations: 19.527 KiB)
    22.0
    

    虽然我已经回答了 OP 的问题,并且 SharedArray 对所有工作人员都是可见的——这合法吗?

    【讨论】:

      猜你喜欢
      • 2016-10-06
      • 2019-08-09
      • 1970-01-01
      • 1970-01-01
      • 2019-10-09
      • 2016-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多