Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
A lockless way of setting a lazily-initialized static global value. It works by using a CompareAndSwap atomic operation with a memory barrier to sync threads' instruction & data caches. If another thread sets the value since we looked at __staticVar, Comp
#import <libkern/OSAtomic.h>
@implementation SomeClass
+ (id) someStaticValueComputedOnFirstAccess
static volatile id __staticVar = nil;
if ( __staticVar == nil )
id var = [[Something alloc] init];
if ( OSAtomicCompareAndSwapPtrBarrier(nil, var, &__staticVar) == false )
[var release]; // already set by another thread, so release this one
return ( __staticVar );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.