2

What I have tried:

@property (nonatomic, assign) int count;

in global queue:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    for (int i = 0; i < 10000; i ++) {
        self.count ++;
    }
});

in main queue:

for (int i = 0; i < 10000; i ++) {
    self.count ++;
}

After these operations finished, the log shows count value is below 20000. because of Data Race (Xcode point it out).

Then I change property from nonatomic to atomic, value still below 20000, without Data Race (Xcode didn't point it out)

So , I have some questions about atomic, which case should we use atomic? which is the best way to use atomic?

KZ.matt
  • 19
  • 2
  • 1
    Remember that `self.count++` is really `[self setCount:[self count] + 1];`. – rmaddy Oct 28 '18 at 04:50
  • @rmaddy so, does it exist locks inside setter method? which kind of lock? – KZ.matt Oct 28 '18 at 06:01
  • @KZ.matt Marked as a dupe, but wanted to point you to the specific detail. What you need is *transactional integrity*, which `atomic` does not provide. In effect, you're looking at the firstName/lastName synchronicity issue. – bbum Oct 29 '18 at 19:16
  • @KZ.matt atomic is thread safe yes, in one sense but not the other. The way in which it is safe is that a getter will return to you a full valid object. The way it is not thread safe is that it is not necessarily locking or protecting the associated property getter and setter while a get or set is taking place, no. So you will still have race issues, but no issues when getting an object / value. This post will help you understand https://stackoverflow.com/a/589392/870565 – pnizzle Oct 30 '18 at 03:53
  • @KZ.matt To fully understand this imagine an atomic property that holds a very large object where the setter takes about 2 seconds. If you call the getter right after the setter, you will get the previous object, or possibly get an object when the setter concludes. If the property was defined as non-atomic then you might get a corrupted object since the deallocation and re-allocation of the previous and new object respectively have not finished yet... So yes, you will still have race issue in both cases, but atomic is safer, though slower in a more complex setup – pnizzle Oct 30 '18 at 03:56

0 Answers0