# How do you preform multiple actions in a thread safe way?

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])

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?

Probably the best you can do there is to create independent copies of all data for each thread, and at the end of your trials keep the best result. Using atomic operations there will cause the threaded operations to pause frequently, probably, and by copying the matrix for each thread you avoid the concurrent access to the memory by each thread.

Use a channel and have each thread write a tuple to the channel, then have an extra thread process those tuples…