Created
January 28, 2019 02:52
-
-
Save yam-liu/628f3c35e48dcdbf34cd59ba110a5ccd 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
// | |
// Created on 2019/1/25. | |
// | |
#import <Foundation/Foundation.h> | |
NS_ASSUME_NONNULL_BEGIN | |
@interface ThreadSafeMutableArray<ObjectType> : NSObject <NSFastEnumeration, NSCopying> | |
+ (instancetype)array; | |
- (void)addObject:(ObjectType)obj; | |
- (void)removeAllObjects; | |
@end | |
NS_ASSUME_NONNULL_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
// | |
// Created on 2019/1/25. | |
// | |
#import "ThreadSafeMutableArray.h" | |
#import <pthread/pthread.h> | |
#define WriteLock(x) \ | |
pthread_rwlock_wrlock(&_rwlock); \ | |
x; \ | |
pthread_rwlock_unlock(&_rwlock) | |
#define ReadLock(x) \ | |
pthread_rwlock_rdlock(&_rwlock); \ | |
x; \ | |
pthread_rwlock_unlock(&_rwlock) | |
@interface ThreadSafeMutableArray () { | |
NSMutableArray *_backedArray; | |
pthread_rwlock_t _rwlock; | |
} | |
@end | |
@implementation ThreadSafeMutableArray | |
+ (instancetype)new | |
{ | |
return [[self alloc] init]; | |
} | |
- (instancetype)init | |
{ | |
self = [super init]; | |
if (self) { | |
_backedArray = [NSMutableArray array]; | |
pthread_rwlock_init(&_rwlock, NULL); | |
} | |
return self; | |
} | |
- (void)dealloc | |
{ | |
pthread_rwlock_destroy(&_rwlock); | |
} | |
#pragma mark - Public apis | |
+ (instancetype)array | |
{ | |
return [self new]; | |
} | |
- (void)addObject:(id)obj | |
{ | |
if (!obj) { | |
return; | |
} | |
WriteLock([_backedArray addObject:obj]); | |
} | |
- (void)removeAllObjects | |
{ | |
WriteLock({ | |
[_backedArray removeAllObjects]; | |
}); | |
} | |
#pragma mark - NSCopying | |
- (id)copyWithZone:(NSZone *)zone | |
{ | |
return _backedArray.copy; | |
} | |
#pragma mark - NSFastEnumeration | |
- (NSUInteger)countByEnumeratingWithState:(nonnull NSFastEnumerationState *)state objects:(id _Nullable __unsafe_unretained * _Nonnull)buffer count:(NSUInteger)len { | |
ReadLock(NSUInteger count = [_backedArray.copy countByEnumeratingWithState:state objects:buffer count:len]); | |
return count; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment