Atomic properties vs thread-safe in Objective-C

In answer to your third paragraph; essentially yes. An atomic number can't be read while a thread is writing the number.

For example, if a thread has written the first two bytes of an atomic four byte number, and a read of that number is requested on another thread, that read has to wait until all four bytes have been written.

Conversely, if a thread has written the first two bytes of a non-atomic four byte number, and a read of that number is requested on another thread at that moment, it will read the first two new data bytes, but will get old data from a previous write operation in the other two bytes.


An atomic property in Objective C guarantees that you will never see partial writes. When a @property has the attribute atomic it is impossible to only partially write the value. The setter is like that:

- (void)setProp:(NSString *)newValue {
    [_prop lock];
    _prop = newValue;
    [_prop unlock];
}

So if two threads want to write the value @"test" and @"otherTest" at the same time, then at any given time the property can only be the initial value of the property or @"test" or @"otherTest". nonatomic is faster but the value is a garbage value and no partial String of @"test"/@"otherTest" (thx @Gavin) or any other garbage value.

But atomic is only thread-safe with simple use. It is not garantueed. Appledoc says the following:

Consider an XYZPerson object in which both a person’s first and last names are changed using atomic accessors from one thread. If another thread accesses both names at the same time, the atomic getter methods will return complete strings (without crashing), but there’s no guarantee that those values will be the right names relative to each other. If the first name is accessed before the change, but the last name is accessed after the change, you’ll end up with an inconsistent, mismatched pair of names.

I never had a problem using atomic at all. I designed the code that way, that there is not problem with atomic properties.