I need to check the sums of different combinations from a matrix, and get the biggest sum out. There are 20!
combinations. I need to thread safely check if the loop’s current sum is bigger than the current sum and if it is, assign both the sum and the index of the corresponding combination.
If I understand correctly, if this is done like this:
using Combinatorics, LinearAlgebra
asize = 5
A = rand(UInt32, asize ,asize )
mutable struct AtomSum
@atomic sum::Int
@atomic ind::Matrix{Bool}
end
currmax = AtomSum(0,[0 0; 0 0])
Threads.@threads for i in collect(permutations(1:asize))
index = I(asize)[i,:]
if (su = sum(A[index])) > currmax.sum
@atomic currmax.sum = su
@atomic currmax.ind = index
end
end
Then lines 12-14 can be executed discontinuously, thus possibly assigning the wrong index to a sum that isn’t necessarily bigger than the previous?
How can I do all three in one thread safe operation?