Skip to content

Instantly share code, notes, and snippets.

@jakebromberg
Last active August 24, 2018 18:54
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save jakebromberg/6de55214434aac5425fc7bfed77d5304 to your computer and use it in GitHub Desktop.
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.
#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;
}
@import Foundation;
@interface ThreadSafe<Value>: NSProxy
- (instancetype)initWithValue:(Value)value;
@property (nonatomic, strong, readonly) Value value;
@end
@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