Last active
August 24, 2018 18:54
Star
You must be signed in to star a gist
Inspired by Chris Lattner's concurrency manifesto, this defines a generic thread-safe object in Objective-C, similar to how Chris describes the behavior of actors.
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 "ThreadSafe.h" | |
int main(int argc, char **argv) { | |
NSNumber *seven = @7; | |
ThreadSafe<NSNumber *> *threadSafeNumber = [[ThreadSafe alloc] initWithValue:seven]; | |
NSLog(@"%@", threadSafeNumber.value.stringValue); | |
return 0; | |
} |
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 Foundation; | |
@interface ThreadSafe<Value>: NSProxy | |
- (instancetype)initWithValue:(Value)value; | |
@property (nonatomic, strong, readonly) Value value; | |
@end |
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
@interface ThreadSafe () | |
@property (nonatomic, strong) dispatch_queue_t queue; | |
@property (nonatomic, strong) id internalValue; | |
@end | |
@implementation ThreadSafe | |
- (instancetype)initWithValue:(id)value { | |
_internalValue = value; | |
_queue = dispatch_queue_create(NULL, 0); | |
return self; | |
} | |
- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel { | |
return [self.internalValue methodSignatureForSelector:sel]; | |
} | |
- (void)forwardInvocation:(NSInvocation *)invocation { | |
dispatch_async(self.queue, ^{ | |
invocation.target = self.internalValue; | |
[invocation invoke]; | |
}); | |
} | |
- (id)value { | |
return self; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment