Deadlock and deadlock
Example: A standard deadlock
-(Void) viewDidLoad {[super viewDidLoad]; dispatch_sync (dispatch_get_main_queue (), ^ {});}
Dispatch_sync (queue, block) does two things
- Add the block to the queue;
- The call thread is blocked. Wait until the block () Execution ends and return to the call thread.
Dispatch_async (queue, block) also does two things:
- Add the block to the queue;
- Return directly to the calling thread (without blocking the calling thread ).
The difference between synchronous distribution and asynchronous distribution is to check whether the call thread is blocked.
We ignore that the main thread is a first-in-first-out (FIFO) method, while the viewdidload method belongs to the main thread. Therefore, the main thread should finish the viewdidload task first, then execute the next one, but if the synchronous execution is added to the main thread, viewdidload needs to be executed first, but viewdidload is waiting for the synchronization to complete, so the deadlock is solved.
So remember this lesson: do not distribute the block to the associated queue of the thread where GCD is called synchronously.