Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

NSMutableArray、和 NSMutableDictionary是线程安全的吗?NSCache呢? #93

Open
tbfungeek opened this issue Feb 13, 2020 · 0 comments

Comments

@tbfungeek
Copy link
Owner

NSMutableArray、和 NSMutableDictionary不是线程安全的,NSCache是线程安全的,在多线程读写的情况,NSMutableArray、和 NSMutableDictionary可以使用dispatch_barrier_async 来封装写操作,使用dispatch_sync来封装读操作,如下所示:

#import "NSSafeMutableArray.h"
@interface NSSafeMutableArray()

@property (nonatomic, strong) NSMutableArray *array;
@property (nonatomic, strong) dispatch_queue_t readWriteQuene;

@end

@implementation NSSafeMutableArray
- (instancetype)init {
   self = [super init];
   if (self) {
       _array = [NSMutableArray array];
       _readWriteQuene = dispatch_queue_create("com.liwb.quene", DISPATCH_QUEUE_CONCURRENT);
   }
   return self;
}

- (void)addObject:(id)anObject {
   dispatch_barrier_async(self.readWriteQuene, ^{
       [self.array addObject:anObject];
   });
}

- (void)insertObject:(id)anObject atIndex:(NSUInteger)index {
   dispatch_barrier_async(self.readWriteQuene, ^{
       [self.array insertObject:anObject atIndex:index];
   });
}

- (id)objectAtIndex:(NSUInteger)index {
   __block id item = nil;
   dispatch_sync(self.readWriteQuene, ^{
       if (index <= self.array.count - 1) {
           item = [self.array objectAtIndex:index];
       }
   });
   return item;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant