GCD相当好用,但用不好就会死锁,始终要记着这样一句秘籍:
不要在串行队列放dispatch_sync、dispatch_apply
下面看几个例子
// 防死锁秘籍:不要在串行队列放dispatch_sync、dispatch_apply
// 死锁 主线程调用dispatch_apply
dispatch_async(dispatch_get_main_queue(), ^{
dispatch_apply(5, dispatch_get_main_queue(), ^(size_t i) {
NSLog(@"%ld",i);
NSLog(@"%d",55);
});
});
NSLog(@"%d",999);
//死锁 主线程调用dispatch_apply
dispatch_apply(5, dispatch_get_main_queue(), ^(size_t i) {
NSLog(@"%ld",i);
NSLog(@"%d",777);
});
//不死锁
dispatch_queue_t queue= dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_apply(5, queue, ^(size_t i) {
NSLog(@"%ld",i);
NSLog(@"%d",66);
});
NSLog(@"%d",88);
//不死锁
dispatch_async(queue, ^{
dispatch_apply(5, dispatch_get_main_queue(), ^(size_t i) {
NSLog(@"%ld",i);
});
});
// //不死锁
dispatch_async(queue,^{
dispatch_sync(dispatch_get_main_queue(), ^{
NSLog(@"test");
});
});
//死锁
dispatch_sync(queue,^{
dispatch_sync(dispatch_get_main_queue(), ^{
NSLog(@"test");
});
});