并行计算示例1:用DistributedArrays.jl做分布式计算

   日期:2020-09-14     浏览:92    评论:0    
核心提示:一个用DistributedArrays.jl做分布式计算的示例,供新手参考。

一个用DistributedArrays.jl做分布式计算的示例,供新手参考。关于如何搭建分布式集群,请参阅之前的博客。

# Example 1: Distributed computing with DistributedArrays.jl
# More instructions: https://juliaparallel.github.io/DistributedArrays.jl/stable/
# ----------

# Set the number of workers.
n = 2

# Use the Distributed package.
using Distributed

# Add workers.
addprocs(n - nprocs() + 1)
println("Opened ", nworkers()," worker(es) of PID ", workers())

# Use the DistributedArrays package everywhere.
@everywhere using DistributedArrays 

# Define a datatype everywhere.
@everywhere mutable struct MyType
    x
    y
    z
end

# Generate an array with arbitary element datatype, for example, MyType.
A = [MyType(0, 0, 0) for i in 1:4, j in 1:4]

# Distribute the array among workers.
DA = distribute(A, procs = [2, 3])

# Perform the computing among workers. Use @sync to synchronize all tasks.
@sync for pid in workers()
    # Send the task to the remote worker whose PID = pid. The task is wrapped in a "begin" block.
    @spawnat pid begin
        # You can read any element of DA directly on any worker.
        for a in DA
            println(a.x)
        end

        # You can modify the element of DA only when the element is stored on the current worker.
        for a in DA
            a.x = myid()
        end

        # To modify the element, it is highly recommended to use localpart() to access the local part of DA on the remote worker.
        for a in localpart(DA)
            a.y = myid()
        end

        # Or use localindices().
        r1, r2 = localindices(DA)
        for i in r1, j in r2
            DA[i, j].z = myid()
        end
    end
end

# You can read DA on any worker.
display(DA)
 
打赏
 本文转载自:网络 
所有权利归属于原作者,如文章来源标示错误或侵犯了您的权利请联系微信13520258486
更多>最近资讯中心
更多>最新资讯中心
0相关评论

推荐图文
推荐资讯中心
点击排行
最新信息
新手指南
采购商服务
供应商服务
交易安全
关注我们
手机网站:
新浪微博:
微信关注:

13520258486

周一至周五 9:00-18:00
(其他时间联系在线客服)

24小时在线客服