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

2018-10-23  本文已影响0人  louuXinnn
#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 <NSThread: 0x600000276840>{number = 3, name = (null)}
 2018-10-23 20:27:26.256531+0800 testttt[6530:334192] 0   <NSThread: 0x600000276840>{number = 3, name = (null)}
 2018-10-23 20:27:26.256547+0800 testttt[6530:334186] BBBB <NSThread: 0x604000270d00>{number = 4, name = (null)}
 2018-10-23 20:27:26.256583+0800 testttt[6530:334184] CCCC <NSThread: 0x604000270dc0>{number = 5, name = (null)}
 2018-10-23 20:27:26.256785+0800 testttt[6530:334192] 1   <NSThread: 0x600000276840>{number = 3, name = (null)}
 2018-10-23 20:27:26.257096+0800 testttt[6530:334192] 2   <NSThread: 0x600000276840>{number = 3, name = (null)}
 2018-10-23 20:27:26.257256+0800 testttt[6530:334192] 3   <NSThread: 0x600000276840>{number = 3, name = (null)}
 2018-10-23 20:27:26.257444+0800 testttt[6530:334192] 4   <NSThread: 0x600000276840>{number = 3, name = (null)}
 2018-10-23 20:27:26.258598+0800 testttt[6530:334192] 5   <NSThread: 0x600000276840>{number = 3, name = (null)}
 2018-10-23 20:27:26.259088+0800 testttt[6530:334192] 6   <NSThread: 0x600000276840>{number = 3, name = (null)}
 2018-10-23 20:27:26.260051+0800 testttt[6530:334192] 7   <NSThread: 0x600000276840>{number = 3, name = (null)}
 2018-10-23 20:27:26.260641+0800 testttt[6530:334192] 8   <NSThread: 0x600000276840>{number = 3, name = (null)}
 2018-10-23 20:27:26.261221+0800 testttt[6530:334192] 9   <NSThread: 0x600000276840>{number = 3, name = (null)}
 */
@end

原因猜想:

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

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

上一篇下一篇

猜你喜欢

热点阅读