问题
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.
Threads (requires setting
JULIA_NUM_THREADS
system variable)arr = Array{Int}(undef, 10) Threads.@threads for i = 1:10 arr[i] = i end
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).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