Search code examples
iosobjective-cthread-safetygrand-central-dispatchatomic

Do we need to declare a property atomic if we use GCD?


Does Grand Central Dispatch care about atomic and nonatomic keywords, or we have to specify atomic anyway?

I know that atomic and nonatomic keywords in property declarations will generate different setters and getters, atomic will be thread safe.


Solution

  • Using atomic is one way to synchronize a property being used from multiple threads. But there are many mechanisms for synchronizing access from multiple threads, and atomic is one with fairly limited utility. I'd suggest you refer to the Synchronization chapter of the Threading Programming Guide for a fuller discussion of alternatives (and even that fails to discuss other contemporary patterns such as GCD serial queues and reader-writer pattern with a custom, concurrent queue).

    Bottom line, atomic is, by itself, neither necessary nor sufficient to ensure thread safety. In general, it has some limited utility when dealing with some simple, fundamental data type (Booleans, NSInteger) but is inadequate when dealing with more complicated logic or when dealing with mutable objects.

    In short, do not assume that you should use atomic whenever you use GCD. In fact, if you use GCD, that generally obviates the need for atomic, which, in fact, will unnecessary and adversely impact performance in conjunction with GCD. So, if you have some property being accessed from multiple threads, you should synchronize it, but the choice of which synchronization technique to employ is a function of the the specific details of the particular situation, and GCD often is a more performant and more complete solution.