如下代碼會引發死鎖async
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.ide
爲何會發生死鎖呢?spa
當在主線程中執行第一個block時,它沒有將控制權返回給當前線程,即主線程;而後又嘗試在主線程中執行第二個block,此時主線程會一直等待queue完成,於是造成死鎖線程