Is an atomic property thread safe? [duplicate]

2019-06-14 20:24发布

问题:

This question already has an answer here:

  • What's the difference between the atomic and nonatomic attributes? 27 answers
  • Atomic properties vs thread-safe in Objective-C 5 answers

I have gone through many answers about atomic and non-atomic properties. But I'm not able to understand whether atomic properties are thread safe? Please explain it with an example.

回答1:

Yes

an / one atomic property is thread-safe. That is what atomicity stands for.

CAUTION

But neither are two atomic properties thread-safe in regards to each other nor are the contents of an atomic property thread-safe. (sounds a bit confusing but has be said)

That means that your are always guaranteed to be able to read a fully functional value from the property, no broken pointer, or intermediary null or whatsoever.

BUT you are not guaranteed that the values inside that atomic property are thread-safe whatsoever. That is a completely different topic.

Making all properties of a class atomic will not at all make the class itself thread-safe.



回答2:

The property accessors are thread-safe. Basically an atomic property is equivalent to this:

- (id)atomicProperty {
    @synchronized(self) {
        return _atomicProperty;
    }
}

- (void)setAtomicProperty:(id)atomicProperty {
    @synchronized(self) {
        _atomicProperty = atomicProperty;
    }
}