Created
May 29, 2009 01:19
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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