Skip to content

Instantly share code, notes, and snippets.

@AlanQuatermain
Created May 29, 2009 01:19
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save AlanQuatermain/119712 to your computer and use it in GitHub Desktop.
Save AlanQuatermain/119712 to your computer and use it in GitHub Desktop.
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