-
-
Save edwardean/a820a5c843d3fb90e5b8197705a7d51a to your computer and use it in GitHub Desktop.
Simple and effective thread-safe proxy that forwards all method invocations inside a locked scope. Definitely not the fastest thread-safe implementation ever.
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 Foundation; | |
@interface NSObject (ThreadSafeProxy) | |
- (instancetype)threadSafe; | |
@end | |
@interface ThreadSafeProxy : NSProxy | |
- (instancetype)initWithObject:(NSObject *)underlaying; | |
@property (readonly) NSObject *underlaying; | |
@property (readonly) NSRecursiveLock *lock; | |
@end | |
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 "ThreadSafeProxy.h" | |
@implementation ThreadSafeProxy | |
- (instancetype)initWithObject:(NSObject *)underlaying { | |
self->_underlaying = underlaying; | |
self->_lock = [NSRecursiveLock new]; | |
return self; | |
} | |
- (NSMethodSignature *)methodSignatureForSelector:(SEL)selector { | |
return [self->_underlaying methodSignatureForSelector:selector]; | |
} | |
- (void)forwardInvocation:(NSInvocation *)invocation { | |
[self->_lock lock]; | |
[invocation invokeWithTarget:self->_underlaying]; | |
[self->_lock unlock]; | |
} | |
@end | |
@implementation NSObject (ThreadSafeProxy) | |
- (instancetype)threadSafe { | |
return (typeof(self))[[ThreadSafeProxy alloc] initWithObject:self]; | |
} | |
@end | |
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
NSMutableArray *processedArray = [[NSMutableArray new] threadSafe]; | |
[existingArray enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(id object, NSUInteger idx, BOOL *stop) { | |
// ... concurrent processing ... | |
[processedArray addObject:object]; | |
}]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment