GCD - execution sequence

GCD经典面试题

{
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"2--%@",[NSThread currentThread]);
NSLog(@"A");
});
NSLog(@"B");
dispatch_queue_t temp = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);

dispatch_sync(temp, ^{
NSLog(@"3--%@",[NSThread currentThread]);
NSLog(@"C");
});

dispatch_async(temp, ^{
NSLog(@"4--%@",[NSThread currentThread]);
NSLog(@"D");
});
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"5--%@",[NSThread currentThread]);
NSLog(@"E");
});

[self performSelector:@selector(method) withObject:nil afterDelay:0.0];
NSLog(@"F");
}

- (void)method {
NSLog(@"G");
}

/============================================================================/

答案有4个,以下为编译结果 !

答案①

// 同步+串行, 同步+并发 均打印以下结果:
B
3--<NSThread: 0x604000061f00>{number = 1, name = main}
C
F
2--<NSThread: 0x604000061f00>{number = 1, name = main}
A
5--<NSThread: 0x604000061f00>{number = 1, name = main}
E
6--<NSThread: 0x604000061f00>{number = 1, name = main}
G
4--<NSThread: 0x600000267100>{number = 3, name = (null)}
D

答案②

// 如若在同步主线程上执行,会线程阻塞
// sync_main_method 会直接崩溃!!!(答案结束)

// 以下为待验证结果
// 此结果验证一直未出现,罗列在此:
B
3--<NSThread: 0x60400007d3c0>{number = 1, name = main}
C
F
4--<NSThread: 0x60000026c500>{number = 3, name = (null)}
D
2--<NSThread: 0x60400007d3c0>{number = 1, name = main}
A
5--<NSThread: 0x60400007d3c0>{number = 1, name = main}
E
6--<NSThread: 0x60400007d3c0>{number = 1, name = main}
G

答案③

// 异步 + 主队列 执行结果:  async_main_method
B
3--<NSThread: 0x60000176d3c0>{number = 1, name = main}
C
F
6--<NSThread: 0x60000176d3c0>{number = 1, name = main}
G
2--<NSThread: 0x60000176d3c0>{number = 1, name = main}
A
5--<NSThread: 0x60000176d3c0>{number = 1, name = main}
E
4--<NSThread: 0x60000173e900>{number = 3, name = (null)}
D

答案④

// 注:由于打印结果不稳定,随机选取两个

// 异步 + 串行 执行结果: async_serial_method
B
2--<NSThread: 0x60000176d3c0>{number = 1, name = main}
3--<NSThread: 0x60000173e900>{number = 3, name = (null)}
A
C
F
5--<NSThread: 0x60000176d3c0>{number = 1, name = main}
E
4--<NSThread: 0x60000173e980>{number = 4, name = (null)}
D

另有BCAEFD,BCFAED,BACEFD ...

// 异步 + 并发 执行结果: async_concurrent_method
B
2--<NSThread: 0x60000176d3c0>{number = 1, name = main}
3--<NSThread: 0x60000173e980>{number = 4, name = (null)}
A
C
5--<NSThread: 0x60000176d3c0>{number = 1, name = main}
F
E
4--<NSThread: 0x60000173e900>{number = 3, name = (null)}
D

另有BCAFED