在下面的代码中,我们有一个可变数组,它被两个并发队列改变。由于并发队列不是线程安全的,因此此代码在理想情况下应该会崩溃,但会在没有任何异常或崩溃的情况下执行。
请帮助我理解这种行为。任何帮助都感激不尽 :-)
@interface ViewController ()
@property(nonatomic, strong) NSMutableArray *arr;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.arr = [NSMutableArray new];
}
-(void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
__weak typeof(self) weakSelf = self;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
for (int i = 0; i < 20000; i++) {
[weakSelf.arr addObject:[NSNumber numberWithInt:i]];
NSLog(@"Added %@", [weakSelf.arr lastObject]);
}
NSLog(@"Final count %ld", [self.arr count]);
});
[self performSelector:@selector(removeObjects) withObject:nil afterDelay:0.1];
}
-(void)removeObjects{
__weak typeof(self) weakSelf = self;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
for (int i = 0; i < 1000; i++) {
if (weakSelf.arr.count > 1) {
[weakSelf.arr removeObjectAtIndex:0];
}
NSLog(@"Remove object");
}
});
}
@end