GCD异步并发队列内加入同步任务的执行顺序

#import "ViewController.h"

@interface ViewController ()
@end

@implementation ViewController
- (void)viewDidLoad {

    //并发队列
    dispatch_queue_t q = dispatch_queue_create("myQueue", DISPATCH_QUEUE_CONCURRENT);
    //异步任务
    dispatch_async(q, ^{
        //同步并发
        dispatch_sync(q, ^{
            NSLog(@"AAAA %@", [NSThread currentThread]);
        });
        //异步并发
        dispatch_async(q, ^{
            NSLog(@"BBBB %@", [NSThread currentThread]);
        });
        //异步并发
        dispatch_async(q, ^{
            NSLog(@"CCCC %@", [NSThread currentThread]);
        });

        for (int i = 0; i < 10; i++) {
            NSLog(@"%d   %@", i, [NSThread currentThread]);
        }
    });
}
/** 打印结果
 2018-10-23 20:27:26.256127+0800 testttt[6530:334192] AAAA {number = 3, name = (null)}
 2018-10-23 20:27:26.256531+0800 testttt[6530:334192] 0   {number = 3, name = (null)}
 2018-10-23 20:27:26.256547+0800 testttt[6530:334186] BBBB {number = 4, name = (null)}
 2018-10-23 20:27:26.256583+0800 testttt[6530:334184] CCCC {number = 5, name = (null)}
 2018-10-23 20:27:26.256785+0800 testttt[6530:334192] 1   {number = 3, name = (null)}
 2018-10-23 20:27:26.257096+0800 testttt[6530:334192] 2   {number = 3, name = (null)}
 2018-10-23 20:27:26.257256+0800 testttt[6530:334192] 3   {number = 3, name = (null)}
 2018-10-23 20:27:26.257444+0800 testttt[6530:334192] 4   {number = 3, name = (null)}
 2018-10-23 20:27:26.258598+0800 testttt[6530:334192] 5   {number = 3, name = (null)}
 2018-10-23 20:27:26.259088+0800 testttt[6530:334192] 6   {number = 3, name = (null)}
 2018-10-23 20:27:26.260051+0800 testttt[6530:334192] 7   {number = 3, name = (null)}
 2018-10-23 20:27:26.260641+0800 testttt[6530:334192] 8   {number = 3, name = (null)}
 2018-10-23 20:27:26.261221+0800 testttt[6530:334192] 9   {number = 3, name = (null)}
 */
@end

原因猜想:

-- 异步并发队列 中加入同步任务
-- 同步任务会占用并阻塞当前线程(打印AAAA)
-- 当同步任务执行完毕
-- 当前被阻塞的任务继续(打印0), 且B C 异步执行

纯粹个人猜想,如有问题请看官指导

你可能感兴趣的:(GCD异步并发队列内加入同步任务的执行顺序)