以下代码会引起死锁
1 dispatch_block_t block = ^{ 2 for (int i = 0; i < 100; i++) { 3 NSLog(@"dispatch_sync:%d", i); 4 } 5 }; 6 7 dispatch_queue_t queue = dispatch_queue_create("FIFO.QUEQE", 0); 8 dispatch_async(queue, block); 9 10 NSLog(@"finish dispatch_asyn"); 11 12 dispatch_sync(dispatch_get_main_queue(), ^{ 13 NSLog(@"sync"); 14 }); 15 16 NSLog(@"finish dispatch_sync");
Apple的官方文档中这么描述:Calls to dispatch_sync() targeting the current queue will result in dead-lock.
为什么会发生死锁呢?
当在主线程中执行第一个block时,它没有将控制权返回给当前线程,即主线程;然后又尝试在主线程中执行第二个block,此时主线程会一直等待queue完成,因而形成死锁