The following (pseudo)code is not thread-safe:
mutable struct MutableState
x::Int
end
function f(state)
y = state.x
z = y^2
state.x = z
end
state = MutableState(3)
# now run f(state) in parallel from many different threads
My question is: how can I make this thread-safe? The key is that I read from state.x
, do something, and then write to it. Can this be done using @atomic
on the field x
, and if so with which memory ordering requirement and on which operations do I put @atomic
? (Just the write, or also the read?)