In Objective-C Does it ever make sense to specify a property for a primitive type as nonatomic
?
I\'m wondering about the difference between these two pr
In a x-bit architecture (eg: 32bit, 64bit, etc.) any value which is x or less bits will always be read or written atomically. This is a property of any sane hardware implementation.
The default atomic property means that a property value is always set or get in whole, disregarding what other threads are doing. This is only a concern for properties that exceed the number of bits of the architecture. Nonatomic is completely ignored by the compiler on any other type.
Example:
@property struct { int d; } flag;
@property (atomic) struct { float x; float y; } point;
@property (atomic,copy) NSString *s;
struct { int d; }
is already atomic so the accesors don't need mutual exclusion.
struct { float x, float y}
could be in an inconsistent state if it wasn't atomic. Example: two threads setting {1,2}
and {3,4}
could overlap the writing, and the struct could end up with a value from each set: {1,4}
.
Atomic properties contribute to thread safety avoiding race conditions that lead to inconsistent values or memory management mishaps. This alone doesn't guarantee thread safety because it doesn't deal with other problems like deadlock, starvation, visibility, etc.