I have the following block of code that I wish to excuite with the help of 6 threads
N = 16^3
z = 0.0
kx = pi/2
ky = 3pi/2
Threads.@threads for k in 1:N
z += cos(dot((kx,ky, 2*pi),pos[k]))
end
This leads to a race condition and every time I run this code, a different value for z
is obtained. This leads me to two questions:
Firstly, why do race conditions appear when just adding terms together. Addition is commutative so it should not matter (at least from a math perspective).
Secondly, what is the best way to resolve this issue. I examined the Julia documentation on multi-threading race conditions and they suggest splitting the vector 1:N
into chunks. However, I find there sample code not intuitive and hard to actually understand what the function itself is doing.