I declared a atomic NSMutableArray to save objects
@property (atomic, strong) NSMutableArray *list;
@synthesize list;
Then I'm using a thread to save object like:
__weak typeof(self) weakSelf = self;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{ // writing files into the disk in background
// do something..
[weakSelf.list addObject:object]; // add object at the end of the list
if (!weakSelf.threadCreateFlag) {
NSInvocationOperation *newoperation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(createThreadMethod) object:nil]; // create thread to remove from the array
[weakSelf.serailQueue addOperation:newoperation];
}
});
And I'm trying to read the object at index 0 and remove it from the array
- (void)createThreadMethod {
self.threadCreateFlag = YES;
do {
NSLog(@"loop");
@autoreleasepool {
NSDictionary *object = (NSDictionary *)[self.list objectAtIndex:0];
[self.list removeObjectAtIndex:0];
// doing something...
}
} while(self.list.count > 0);
self.photoSavingLock = NO;
}
I am confronted with an issue - sometimes, the array contains object 0x0, and my app will crash.
I did some research about it, I think because removeObjectAtIndex
is not thread-safe. So I'm trying to add a global @property (atomic, strong) NSLock *lock
around read/remove and add function.
But this time I got [NSLock deadlock]
.
What is the proper way to make this scenario thread-safe?