How to write to multiple indices of an array at the same time in Julia?

ⅰ亾dé卋堺 提交于 2020-12-10 05:03:08

问题


I would like to see something like this working in Julia:

using Distributed
addprocs(4)

@everywhere arr = Array{Int}(undef, 10)
for i = 1:10
    @spawn arr[i] = i
end

What is the proper way of doing this?


回答1:


You have the following ways to parallelize the process.

  1. Threads (requires setting JULIA_NUM_THREADS system variable)

    arr = Array{Int}(undef, 10)
    Threads.@threads for i = 1:10
        arr[i] = i
    end
    
  2. SharedArrays

    using Distributed, SharedArrays
    addprocs(4)
    arr = SharedVector{Int}(10)
    @sync @distributed for i in 1:10
        arr[i] = i 
    end
    

    Note that a common error is to forget to place @sync before @distributed that does not have an aggregator function (see the last example).

  3. Aggregate the results of your distributed computation

    using Distributed
    addprocs(4)
    arr = @distributed (append!) for i in 1:10
        [i]
    end
    


来源:https://stackoverflow.com/questions/64499815/how-to-write-to-multiple-indices-of-an-array-at-the-same-time-in-julia

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!