I need to have multiple threads write values to a shared array. I’m thinking of having each thread write to a private array, and then have the threads each write their private values into a shared array. In the following example I’ve chosen values that assume 2 threads, and I’m assuming thread 1 has written the values 1 and 2, and thread 2 has written the values 3, 4, 5. A prefix sum is used to let each thread know where to start writing in the shared array (b
).
using Base.Threads
function copyVerts!(b, subarray, start, nper, id)
for i in 1:nper[id]
b[start[id]+i] = subarray[id][i]
end
end
# assuming nthreads() is 2
b = Array{Int64,1}(undef,5)
subarray = [similar(b, 0) for i = 1:Threads.nthreads()]
subarray[1] = [1,2]
subarray[2] = [3,4,5]
nper = [2,3] # thread 1 has 2 values and thread 2 has 3 values
start = cumsum(nper) - nper # exclusive prefix sum
for i = 1:nthreads()
Threads.@spawn copyVerts!(b, subarray, start, nper, i)
end
This gives:
julia> b
5-element Array{Int64,1}:
1
2
3
4
5
Is this a good solution, and how do I wait for all tasks to complete? Feedback would be appreciated.