Learn about GCD synchronous asynchrony first
  • Dispatch_async Function that performs tasks asynchronously.

    • The next statement can be executed without waiting for the current statement to complete.
    • Thread execution is startedblockThe task.
    • Asynchrony is a byword for multithreading.
  • Dispatch_sync Synchronization function.

    • You must wait for the current statement to complete before executing the next statement.
    • The thread will not be started.
    • Execute at presentblockTask.
  • A block block is executed inside a function.

The normal code is as follows

Create a concurrent queue and add it to the asynchronous function with three tasks in it. The NSLog (@ “2”); ` ` Block, Block NSLog (@ “4”);

Code:

dispatch_queue_t queue = dispatch_queue_create("bobo", DISPATCH_QUEUE_CONCURRENT);
    NSLog(@"1");
    dispatch_async(queue, ^{
        NSLog(@"2");
        dispatch_sync(queue, ^{
           NSLog(@"3");
        });
        NSLog(@"4");
    });
    NSLog(@"5");
Copy the code

The result is 1, 5, 2, 3, 4

Results analysis:

The code is executed from the top down, first printing 1, since it is an asynchronous function, there is no thread waiting (protection), so it continues to print 5, then executes the task inside the asynchronous function, first printing 2, and then encounters the synchronous function (must wait for the current statement to complete, will execute the next statement), So the Block is executed before it can execute 4 so it prints 3 and then 4

GCD deadlock code

Change the above code concurrent to serial

The code is as follows:

DISPATCH_QUEUE_CONCURRENT // Serial DISPATCH_QUEUE_SERIAL deadlocked dispatch_queue_t queue = dispatch_queue_create("bobo", DISPATCH_QUEUE_SERIAL); NSLog(@"1"); dispatch_async(queue, ^{ NSLog(@"2"); dispatch_sync(queue, ^{ NSLog(@"3"); }); NSLog(@"4"); }); NSLog(@"5");Copy the code

The result is 1, 5, 2 deadlocks

Results analysis:

To perform a task 1, serial queue, and then execute asynchronous functions, an asynchronous function don’t have to wait for, five tasks, execute asynchronous function again, because it is a serial (FIFO), first in first out principle, first 2 tasks, block, block mission again, 4 mission again, because the block is synchronous function (must wait for the current statement execution is completed, The serial queue task is now task 2, task block, task 4, task 3, and task 4 is before task 3, so task 3 has to wait for task 4 to finish. 4 waits for the block to end. The block waits for the task 3 to end before moving 4. Therefore, a deadlock (dispatch_sync_slow) occurs