dispatch_sync may result in dead-lock

以下代码会引起死锁

  dispatch_block_t block = ^{
for (int i = ; i < ; i++) {
NSLog(@"dispatch_sync:%d", i);
}
}; dispatch_queue_t queue = dispatch_queue_create("FIFO.QUEQE", );
dispatch_async(queue, block); NSLog(@"finish dispatch_asyn"); dispatch_sync(dispatch_get_main_queue(), ^{
NSLog(@"sync");
}); NSLog(@"finish dispatch_sync");

Apple的官方文档中这么描述:Calls to dispatch_sync() targeting the current queue will result in dead-lock.

为什么会发生死锁呢?

当在主线程中执行第一个block时,它没有将控制权返回给当前线程,即主线程;然后又尝试在主线程中执行第二个block,此时主线程会一直等待queue完成,因而形成死锁

上一篇:学习Java第六周


下一篇:Webdriver之API详解(3)