I’ve attempted to understand the Julia docs on the newish @atomic
stuff multiple times and yet I’m still struggling to fully understand. The docs are actually quite sparse on the topic, and what’s worse is that they point to the ‘atomics manifesto’ design document, which is clearly only partially implemented in Julia at present.
As an example, I have:
struct Result
score::Int
action::Union{Int, Nothing}
end
Base.isless(r1::Result, r2::Result) = isless(r1.score, r2.score)
And I want to atomically set the maximum result from within multithreaded code, e.g.:
best::Result = max(best, candidate)
The manifesto suggests I could do something like
(@atomic best)::Result = Result(typemin(Int), nothing)
@atomic max(best, candidate)
Unfortunately, this isn’t yet supported. So it looks like I’m forced to create a wrapper struct with the field marked as atomic, eg.
struct Best
@atomic result::Result
end
@atomic best = Best(Result(typemin(Int), nothing))
@atomic max(best.result, candidate)
However, this JuliaCon talk suggests there are cases where atomic lines (like @atomic a.x = a.x + 2
) are not thread safe. In lieu of better documentation, it’s not at all clear to me when my code will be threadsafe - and I’m unsure if the above code is itself threadsafe.
What’s the best way to do something like this?