Hi, I am fairly new to multi-threading in Juila and am having trouble finding the best procedure to avoid data races in an a section of code I am writing.
The code uses a monte carlo method to generate values that are then assigned to specific locations in a large 6D array based on some conditions and a second array is used to keep a tally of sampled points. Something like (I cannot share the actual code):
lk = ReentrantLock()
Threads.@threads :static for iThreads in 1:nThreads
generatevalues!(val,somedata)
(loc1,loc2,loc3,loc4,loc5,loc6,somedata)=generatelocations(somedata)
#update arrays
begin
lock(lk)
try
if (1<=loc1<=num1)
ArrayofValues[loc1+2,loc2,loc3,loc4,loc5,loc6] += val
elseif (loc1 > num1)
ArrayofValues[2,loc2,loc3,loc4,loc5,loc6] += val
else (loc1 < num1)
ArrayofValues[1,loc2,loc3,loc4,loc5,loc6] += val
end
@view(ArrayofTallys[:,loc2,loc3,loc4,loc5,loc6] .+= 1
finally
unlock(lk)
end
end
These arrays are large but in general so the likelihood of two threads editing the same elements of the arrays at the same time is low but non-zero, hence the use of the lock. However this tends to makes the code slower than the serial version. Is there an efficient way to edit small sections/views of arrays without needing to lock the whole thing? Or is there a better approach that I should attempt to take?
edits: square brackets for array indexing.