Taking Notes

cause i'll forget

Keeping Count With OSAtomic

OSAtomic is a many splendored thing, with many low level functions to simplify manipulating your data in a thread safe manner.


One of the things it does best is make integer math really easy to do without the weight of a general purpose lock.

Here’s a dead simple counter that just bumps an integer on each access:

#import <Foundation/Foundation.h>
#import <libkern/OSAtomic.h>

static int32_t _count = 0;
static inline int32_t MonotonicCounter(void)
    return OSAtomicIncrement32(&_count);

OSAtomic is worth spending some time with, there’s lots of goodies.