tofucodes tofucodes -4 years ago 159
iOS Question

When to use @atomic?

I've already seen this question:

What's the difference between the atomic and nonatomic attributes?

I understand that

does not guarantee thread safe, and I have to use other mechanisms (e.g.
) to realize that. Based on that, I don't still know EXACTLY when to use
attribute. I'd like to know USE CASE of using

Answer Source

The typical use-case for atomic properties is when dealing with a primitive data type across multiple threads. For example, let's say you have some background thread doing some processing and you have some BOOL state property, e.g. isProcessComplete and your main thread wants to check to see if the background process is complete:

if (self.isProcessComplete) {
    // Do something

In this case, declaring this property as atomic allows us to use/update this property across multiple threads without any more complicated synchronization mechanism because:

  • we're dealing with a scalar, primitive data type, e.g. BOOL;
  • we declared it to be atomic; and
  • we're using the accessor method (e.g. self.) rather than accessing the ivar directly.

When dealing with objects or other more complicated situations, atomic generally is insufficient. As you point out, in practice, atomic, alone, is rarely sufficient to achieve thread safety, which is why we don't use it very often. But for simple, stand-alone, primitive data types, atomic can be an easy way to ensure safe access across multiple threads.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download