gpt4 book ai didi

arrays - Julia中的共享数组用法

转载 作者:行者123 更新时间:2023-12-04 07:19:23 26 4
gpt4 key购买 nike

我需要将某些任务分配给许多 worker 。
为此,我需要所有工作人员都可以访问存储数据的矩阵。

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

为了让我开始使用共享阵列,我正在尝试以下非常简单的示例,该示例为我提供了意外的行为:

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应该对所有工作人员都可见?
我显然缺少基本的东西。提前致谢。

最佳答案

尽管基础数据已共享给所有工作程序,但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

关于arrays - Julia中的共享数组用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35751420/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com