Atomic Counters in Objective-C
Atomic counters are useful for managing state across multiple threads. In this example, we’ll look at using atomic operations to safely increment a counter accessed by multiple threads.
In this Objective-C version:
We use
int64_t
as our counter type, which is a 64-bit integer.Instead of Go’s WaitGroup, we use a Grand Central Dispatch (GCD) group (
dispatch_group_t
) to wait for all threads to complete.We replace Go’s goroutines with GCD’s
dispatch_group_async
, which allows us to dispatch blocks of code to be executed concurrently.For atomic incrementation, we use
OSAtomicIncrement64
from thelibkern/OSAtomic.h
header. This function atomically increments the 64-bit integer.We use
NSLog
for output instead of Go’sfmt.Println
.
When you run this program, you should see:
We expect to get exactly 50,000 operations. If we had used a non-atomic integer and incremented it with regular addition, we’d likely get a different number, changing between runs, because the threads would interfere with each other.
Note that in more recent versions of iOS and macOS, Apple recommends using stdatomic.h
for atomic operations. However, OSAtomic
functions are still widely used and are more similar to the Go example in terms of API.
Next, we could look at other synchronization primitives in Objective-C, such as locks or semaphores, for managing state across threads.