Created
August 28, 2010 09:05
-
-
Save Kentzo/554925 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 "MABaseFuture.h" | |
| #import <libkern/OSAtomic.h> | |
| @implementation MABaseFuture | |
| @dynamic futureValue; | |
| @synthesize futureHasResolved = _resolved; | |
| - (id)futureValue | |
| { | |
| OSMemoryBarrier(); | |
| return _resolved ? _value : nil; | |
| } | |
| - (void)setFutureValue: (id)value | |
| { | |
| [value retain]; | |
| [_value release]; | |
| _value = value; | |
| OSMemoryBarrier(); | |
| _resolved = YES; | |
| [_lock broadcast]; | |
| } | |
| - (id)init | |
| { | |
| _lock = [[NSCondition alloc] init]; | |
| return self; | |
| } | |
| - (void)dealloc | |
| { | |
| [_value release]; | |
| [_lock release]; | |
| [super dealloc]; | |
| } | |
| - (void)waitForFutureResolution | |
| { | |
| [_lock lock]; | |
| while(!_resolved) | |
| [_lock wait]; | |
| [_lock unlock]; | |
| } | |
| - (id)resolveFuture | |
| { | |
| if (!_resolved) { | |
| switch (OSAtomicIncrement32(&_threads)) { | |
| case 1: // Start resolving process. | |
| [self resolveFutureUnlocked]; // Lock/unlock dance should be done inside the block | |
| break; | |
| default: // Wait until future is resolved. | |
| [self waitForFutureResolution]; | |
| break; | |
| } | |
| OSAtomicDecrement32Barrier(&_threads); | |
| } | |
| return _value; | |
| } | |
| - (void)resolveFutureUnlocked | |
| { | |
| NSAssert1(NO, @"-[MABaseFuture resolveFutureUnlocked] called, this should never happen! Did you forget to implement -[%@ resolveFutureUnlocked]?", NSStringFromClass(isa)); | |
| __builtin_unreachable(); | |
| } | |
| - (Class)class | |
| { | |
| Class c = [[self resolveFuture] class]; | |
| if([NSStringFromClass(c) hasPrefix: @"NSCF"]) | |
| return [c superclass]; | |
| else | |
| return c; | |
| } | |
| @end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment