A GCD pen test questions

dispatch_queue_t queue = dispatch_queue_create("com.ihunyu.test", DISPATCH_QUEUE_CONCURRENT);
    NSLog(@"1");
    dispatch_async(queue, ^{
        NSLog(@"2");
        dispatch_async(queue, ^{
            NSLog(@"3");
        });
        NSLog(@"4");
    });
    NSLog(@"5");

Output: 15243
Analysis: After printing the 1, queue asynchronous parallel execution, it creates a new thread, but this will be time consuming, so the first print 5, 2 and then print the same token, there is also creating a new dispatch_async thread, but require time-consuming, so the first print after print 4 3. Where (1,5) in the main thread print, (2,4) to print a new thread in the newly opened, (3) has opened a new print in another thread.

dispatch_queue_t queue = dispatch_queue_create("com.ihunyu.test", DISPATCH_QUEUE_CONCURRENT);
    NSLog(@"1");
    dispatch_async(queue, ^{
        NSLog(@"2");
        dispatch_sync(queue, ^{
            NSLog(@"3");
        });
        NSLog(@"4");
    });
    NSLog(@"5");

Output: 15234
Analysis: same as the first example, prints 152, inside dispatch_sync concurrent synchronous execution queue, the new thread can not be opened, only serial execution, and the like need to perform after the innermost block after, that is, print 3, will continue to print 4. Where (1,5) in the main thread print, (2,3,4) to print a new thread in that newly opened.

dispatch_queue_t queue = dispatch_queue_create("com.ihunyu.test", DISPATCH_QUEUE_SERIAL);
    NSLog(@"1");
    dispatch_async(queue, ^{
        NSLog(@"2");
        dispatch_sync(queue, ^{
            NSLog(@"3");
        });
        NSLog(@"4");
    });
    NSLog(@"5");

Output: 1 5 2 crash
Analysis: First print 1, then the serial asynchronous execution queue, to create a new thread, serial execution. But time-consuming, so the first print 5, and then print 2. Then the serial synchronous execution queue, you can not create a new thread in the outer layer block waiting for executing the block will be implemented, such as the inner layer of the outer block executing the block will be implemented, resulting in a deadlock.

Published 103 original articles · won praise 55 · views 380 000 +

Guess you like

Origin blog.csdn.net/dolacmeng/article/details/89516854