造成死锁的各种情况

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

dispatch_sync(queue, ^{/* a task */});

After the dispatch_sync function is called, the function doesn’t return until the specified task is finished. It is like a brief version of the dispatch_group_wait function. As you see, the source code is very simple. You can use the dispatch_sync function very easily although it can produce a problem called deadlock. For example, when the following source code is executed on the main thread, it causes a deadlock.

dispatch_queue_t queue = dispatch_get_main_queue(); dispatch_sync(queue, ^{NSLog(@"Hello?");});

This source code adds a Block to the main dispatch queue; that is, the Block will be executed on the main thread. At the same time, it waits for the block to be finished. Because it is running on the main thread, the Block in the main dispatch queue is never executed. Let’s see the other example:

dispatch_queue_t queue = dispatch_get_main_queue(); dispatch_async(queue, ^{

dispatch_sync(queue, ^{NSLog(@"Hello?");}); });

The Block that is running on the main dispatch queue is waiting for the other Block to be finished, which will run on the main dispatch queue as well. It causes deadlock. 

原文地址:https://www.cnblogs.com/studyNT/p/4633971.html