IOS dispatch_sync (dispatch_get_main_queue (), ^ {}); cause of deadlock
1:
-(Void) viewDidLoad {
// Dispatch_sync (dispatch_get_main_queue (), ^ {
// NSLog (@ 3 );
// Cause of deadlock
// 1: dispatch_sync is waiting for the block statement to be executed, and the block statement must be executed in the main thread. Therefore, if dispatch_sync is called in the main thread, a deadlock will occur.
// 2: dispatch_sync is synchronous and will block the current thread, that is, the main thread. Another block is inserted into the main thread, so a deadlock occurs.
//});
// Dispatch_async (dispatch_get_global_queue (), ^ {
// Async creates an asynchronous thread in the main thread to join the global concurrent queue. async does not wait until the block execution is complete and returns immediately
NSLog (@ 2); // no deadlock occurs;
});
}
Analyze this code: view DidLoad inserts a synchronization thread to dispatch_get_main_queue () during sync in the main thread. sync will wait until the subsequent block execution is complete.. Sync is in the main queue again. It is a serial queue, and sync is added later. The first is the main thread. Therefore, to execute the block in sync, you must wait for the previous main thread to complete the execution, but the main thread
Wait for sync to return and execute the subsequent work, resulting in a deadlock.
2:
Difference between dispatch_sync and dispatch_async:
Dispatch_async (queue, block) async asynchronous queue,dispatch_async
The function returns immediately, and the block is asynchronously executed in the background.
Dispatch_sync (queue, block) sync synchronization queue,dispatch_sync
The function does not return immediately, that is, it blocks the current thread and waits for the block to be executed synchronously.
3:
There are three types of GCD Queue:
1. The main queue: The main queue column. The main thread is in a queue.
2. Global queues: Global concurrency queue.
3. user queue: Use a functiondispatch_queue_create
Custom queue created