8

If I use

@property (atomic,assign) int value;

and later access it like so

self.value--;

is that decrement atomic? Because if I had to do this:

self.value = self.value - 1;

then I am sure there would be a chance of a race condition between the read and the write.

My instinct of course is to just do this

@synchronized(self) { value--; }

but I am being told that is not kosher.

Thanks.

1 Answers1

14

Try OSAtomicIncrement and OSAtomicDecrement as described in this article from Apple.

self.value = self.value - 1;          

will not be atomic regardless of how the property is defined.

Sangram Shivankar
  • 3,245
  • 3
  • 22
  • 36
Brian Walker
  • 8,108
  • 2
  • 30
  • 34
  • 1
    Cool. (upvoted.) I did not know about those atomic operations. Much cleaner than dealing with locks for something as simple as an increment. – Duncan C Jun 12 '12 at 00:24
  • 1
    Just be aware that _everybody_ writing to the value must use the same style of atomic operation. If your thread uses OSAtomicIncrement and mine uses @synchronized (self) { self.value += 1; } it won't work. Probably best to make it a read-only property with a method which performs an atomic add. – gnasher729 Feb 24 '14 at 10:15