I believe I understand the behavior of atomic properties (and vs nonatomic ones) but I am somewhat confused by frequent reference to the notion that atomicity "does not guarantee thread safety". This statement, made often in the context of explaining atomic properties confuses me a bit, because to my read, in the obvious sense, thread safety at the property is exactly what you're getting (though no more).
My understanding is that:
An
atomic
property (which is the default, versus an explicitnonatomic
) is guaranteed to never read back a garbage value due to multiple writer threads. In other words, if the write of the value itself requires multiple steps (like multiple word writes in memory), that write will be atomic. Thus a read of the property from a given thread will always reflect a value that was written in its entirety at some point in the past, although of course a subsequent read may show some different value.If reading (or indeed writing) a property is part of an operation that requires any further guarantees-- for example, updating two properties that are semantically linked, or needing to act on the current value of a property which must be assumed to be held constant until the act is complete-- then further locking or synchronization on the part of the programmer is required for the semantics overall to be thread safe.
In other words, the writing and reading of the atomic property itself is, in fact, "thread safe" (protected from corruption by multiple writers) but of course that protection doesn't extend to any broader logic.
- Is this an accurate understanding?
- Under what broad circumstances is an
atomic
property actually useful? I could contrive some simple examples where a property is some sort of counter or changing object that doesn't need to reflect current state, etc, but those seem uncommon versus multithreading scenarios where you really do need explicit locking around the access-- in which case you could have just usednonatomic
on the actual property all along. - Why exactly do people consistently say that atomicity doesn't "guarantee thread safety"? That seems only true in the same way that an
NSLock
doesn't guarantee thread safety orsynchronized
doesn't guarantee thread safety-- a warning for the uninitiated? Otherwise it seems a confusing designation since the very point of these synchronization mechanisms is that they are for use in thread safe design and they are known to be reliable in their designed operation.
Rob Napier's answer here suggests agreement with #2 above. Would appreciate someone well versed in practical usages of atomic
to let me know if I've got the right idea here.
nonatomic
. :) – matt