Hello!
In the following piece of code, I noticed that adding Threads.@threads
would lead to the wrong result. My limited understanding is that it is because my arrays are not “thread-safe” - I want to learn how to make them so. The code is given below:
using CellListMap
using StaticArrays
N = 100
points = rand(SVector{3,Float64},N)
system = InPlaceNeighborList(x=points, cutoff=0.5, parallel=false)
list = neighborlist!(system)
# List is an vector of tuples in the format of; (index of point i, index of point j, euclidean distance between i and j)
result_single_thread = zeros(N)
for L in list
i = L[1]; j = L[2]; d = L[3]
result_single_thread[i] += d
result_single_thread[j] += d
end
result_multi_thread = zeros(N)
Threads.@threads for L in list
i = L[1]; j = L[2]; d = L[3]
result_multi_thread[i] += d
result_multi_thread[j] += d
end
deviance_between_single_and_multi_thread = sum(result_single_thread .- result_multi_thread)
println("Deviance between single and multi thread")
println(deviance_between_single_and_multi_thread)
println("Sum SINGLE: $(sum(result_single_thread))")
println("Sum SINGLE: $(sum(result_multi_thread))")
Which returns:
Deviance between single and multi thread
17.944560782803904
Sum SINGLE: 1050.8378293270782
Sum MULTI: 1032.8932685442744
Which means that my result using the multi-threaded approach is wrong.
How would I fix this issue?
Kind regards