Julia:如何将数据复制到Julia中的另一个处理器

bde*_*vic 33 parallel-processing julia

如何在julia中将数据从一个处理器移动到另一个处理器?

说我有一个阵列

a = [1:10]
Run Code Online (Sandbox Code Playgroud)

或者其他一些数据结构.将它放在所有其他可用处理器上的正确方法是什么,以便它们可以作为相同的变量名在这些处理器上使用?

spe*_*on2 34

起初我不知道该怎么做,所以我花了一些时间搞清楚.

以下是我编写的用于传递对象的一些函数:

sendto

将任意数量的变量发送到指定的进程.

在指定进程的Main模块中创建新变量.名称将是关键字参数的键,值将是关联的值.

function sendto(p::Int; args...)
    for (nm, val) in args
        @spawnat(p, eval(Main, Expr(:(=), nm, val)))
    end
end


function sendto(ps::Vector{Int}; args...)
    for p in ps
        sendto(p; args...)
    end
end
Run Code Online (Sandbox Code Playgroud)

例子

# creates an integer x and Matrix y on processes 1 and 2
sendto([1, 2], x=100, y=rand(2, 3))

# create a variable here, then send it everywhere else
z = randn(10, 10); sendto(workers(), z=z)
Run Code Online (Sandbox Code Playgroud)

getfrom

检索任意进程中任意模块中定义的对象.默认为主模块.

要检索的对象的名称应该是符号.

getfrom(p::Int, nm::Symbol; mod=Main) = fetch(@spawnat(p, getfield(mod, nm)))
Run Code Online (Sandbox Code Playgroud)

例子

# get an object from named x from Main module on process 2. Name it x
x = getfrom(2, :x)
Run Code Online (Sandbox Code Playgroud)

passobj

将任意数量的对象从一个进程传递到任意进程.该变量必须from_mod在src进程的模块中定义,并将以相同的名称复制到to_mod 每个目标进程的模块上.

function passobj(src::Int, target::Vector{Int}, nm::Symbol;
                 from_mod=Main, to_mod=Main)
    r = RemoteRef(src)
    @spawnat(src, put!(r, getfield(from_mod, nm)))
    for to in target
        @spawnat(to, eval(to_mod, Expr(:(=), nm, fetch(r))))
    end
    nothing
end


function passobj(src::Int, target::Int, nm::Symbol; from_mod=Main, to_mod=Main)
    passobj(src, [target], nm; from_mod=from_mod, to_mod=to_mod)
end


function passobj(src::Int, target, nms::Vector{Symbol};
                 from_mod=Main, to_mod=Main)
    for nm in nms
        passobj(src, target, nm; from_mod=from_mod, to_mod=to_mod)
    end
end
Run Code Online (Sandbox Code Playgroud)

例子

# pass variable named x from process 2 to all other processes
passobj(2, filter(x->x!=2, procs()), :x)

# pass variables t, u, v from process 3 to process 1
passobj(3, 1, [:t, :u, :v])

# Pass a variable from the `Foo` module on process 1 to Main on workers
passobj(1, workers(), [:foo]; from_mod=Foo)
Run Code Online (Sandbox Code Playgroud)

  • @ user1438310为此我做了[ParallelDataTransfer.jl](https://github.com/ChrisRackauckas/ParallelDataTransfer.jl).目前,测试在v0.4.x上失败,但是传递到v0.5.人们可以添加更多以使其更好. (3认同)
  • 这些宏非常有用,它们应该成为一个包甚至是Julia的一部分! (2认同)

Chr*_*kas 10

这里的每个人都知道,我把这些想法放在一个包ParallelDataTransfer.jl中.所以你只需要做

using ParallelDataTransfer
Run Code Online (Sandbox Code Playgroud)

(安装后)以便使用此处答案中提到的功能.为什么?这些功能非常有用!我添加了一些测试,一些新的宏,并稍微更新了它们(它们传递到v0.5,在v0.4.x上失败).随意放入拉动请求来编辑这些并添加更多.


小智 9

使用@eval @everywhere...和转义局部变量.像这样:

julia> a=collect(1:3)
3-element Array{Int64,1}:
  1
  2
  3

julia> addprocs(1)
1-element Array{Int64,1}:
 2

julia> @eval @everywhere a=$a

julia> @fetchfrom 2 a
3-element Array{Int64,1}:
 1
 2
 3
Run Code Online (Sandbox Code Playgroud)