2

What does OSAtomicIncrement32 lock on? Does dispatch_async cause atomic calls to be not thread safe for the original variable?

static volatile int32_t count;
...
dispatch_async(dispatch_get_main_queue(), ^{
  ...
  OSAtomicIncrement32(&count);
}

Is volatile redundant, or could some threads read an old value even if count is always atomically incremented?

Edit: the volatile question was cleared up by http://www.drdobbs.com/parallel/volatile-vs-volatile/212701484. That can be found by following several links in the answer, but thought I'd post it here for quick reference. In short, 'volatile' does not mean the same thing in Java as in Objective-C.

mbarrows
  • 555
  • 5
  • 15
  • 5
    It doesn't lock on anything. It uses a CPU instruction that updates the memory and causes other CPUs/cores/etc to see the new value. – Avi Mar 09 '16 at 19:34

1 Answers1

5

From Apple documentation:

Nonblocking synchronization is a way to perform some types of operations and avoid the expense of locks. Although locks are an effective way to synchronize two threads, acquiring a lock is a relatively expensive operation, even in the uncontested case. By contrast, many atomic operations take a fraction of the time to complete and can be just as effective as a lock.

Atomic operations let you perform simple mathematical and logical operations on 32-bit or 64-bit values. These operations rely on special hardware instructions (and an optional memory barrier) to ensure that the given operation completes before the affected memory is accessed again. In the multithreaded case, you should always use the atomic operations that incorporate a memory barrier to ensure that the memory is synchronized correctly between threads.

So, you should use OSAtomicIncrement32Barrier to ensure that memory shared between threads is properly synchronized. According this answer, you should use non-barrier function only if argument is not used to access any other data

See answers to this question regarding volatile keyword usage with atomic operations.

Community
  • 1
  • 1
Borys Verebskyi
  • 4,160
  • 6
  • 28
  • 42
  • 1
    Also note that the as of macOS 10.12 the `OSAtomic`... APIs have been deprecated in favor of the kernel's `atomic_` functions. see `man 3 stdatomic` – James Bucanek May 27 '18 at 18:56