你没有提供一个最低限度的工作例子,但我想这可能很难。这是我的。假设我们想使用
Distributed
计算…的和
Array
的列:
using Distributed
addprocs(2)
@everywhere using StatsBase
data = rand(1000,2000)
res = zeros(2000)
@sync @distributed for col = 1:size(data)[2]
res[col] = StatsBase.mean(data[:,col])
# does not work!
# ... because data is created locally and never returned!
end
为了更正上面的代码,您需要提供一个聚合器函数(我故意简化了示例-可以进行进一步优化)。
using Distributed
addprocs(2)
@everywhere using Distributed,StatsBase
data = rand(1000,2000)
@everywhere function t2(d1,d2)
append!(d1,d2)
d1
end
res = @sync @distributed (t2) for col = 1:size(data)[2]
[(myid(),col, StatsBase.mean(data[:,col]))]
end
2
当其他人在工作时
3
:
julia> res
2000-element Array{Tuple{Int64,Int64,Float64},1}:
(2, 1, 0.49703681326230276)
(2, 2, 0.5035341367791002)
(2, 3, 0.5050607022354537)
â®
(3, 1998, 0.4975699181976122)
(3, 1999, 0.5009498778934444)
(3, 2000, 0.499671315490524)
进一步可能的改进/修改:
-
@spawnat
在远程进程生成值(而不是主进程并发送它们)
-
SharedArray
-这允许在工作人员之间自动分发数据。根据我的经验,需要非常仔细的编程。
-
使用
ParallelDataTransfer.jl
-
始终考虑Julia线程机制(在某些情况下,它使生活更轻松-同样取决于问题)