NSLog(@"--主线程: %@", [NSThread currentThread]);
dispatch_queue_t serialQueue = dispatch_queue_create("com.objcc.serial1", DISPATCH_QUEUE_SERIAL);
dispatch_queue_t concurrentQueue = dispatch_queue_create("com.objcc.concurrent1", DISPATCH_QUEUE_CONCURRENT);
//1. 异步并发嵌套同一个同步并发(异步并发创建新线程,同步并发没有创建新线程)
dispatch_async(concurrentQueue, ^{
NSLog(@"--异步并发: %@", [NSThread currentThread]);
dispatch_sync(concurrentQueue, ^{
NSLog(@"--同步并发: %@", [NSThread currentThread]);
});
});
//2. 异步并发嵌套同同一个异步并发队列(外层创建新线程,内层不创建新线程)
dispatch_async(concurrentQueue, ^{
NSLog(@"--异步并发1: %@",[NSThread currentThread]);
dispatch_async(concurrentQueue, ^{
NSLog(@"--异步并发2: %@",[NSThread currentThread]);
});
});
//3. 同步并发嵌套同一个同步并发队列(都不会开启新线程)
dispatch_sync(concurrentQueue, ^{
NSLog(@"--同步并发1: %@",[NSThread currentThread]);
dispatch_sync(concurrentQueue, ^{
NSLog(@"--同步并发1: %@",[NSThread currentThread]);
});
});
//3. 同步并发嵌套异步并发(异步并发会开启新线程)
dispatch_sync(concurrentQueue, ^{
NSLog(@"--同步并发1: %@",[NSThread currentThread]);
dispatch_async(concurrentQueue, ^{
NSLog(@"--异步并发2: %@",[NSThread currentThread]);
});
});
//4. 异步串行,嵌套同一个同步串行(外环开启新线程,内环死锁卡崩溃)
dispatch_async(serialQueue, ^{
NSLog(@"--异步串行1: %@",[NSThread currentThread]);
dispatch_sync(serialQueue, ^{
NSLog(@"--同步串发2: %@",[NSThread currentThread]);
});
});
//6. 异步串行嵌套同一个异步串行(外环开启新线程,内环在外环的线程中)
//2021-05-25 21:54:17.658046+0800 GcdDemo[51591:6655010] --异步串行1: <NSThread: 0x6000033ad400>{number = 6, name = (null)}
//2021-05-25 21:54:17.658177+0800 GcdDemo[51591:6655010] --异步串行2: <NSThread: 0x6000033ad400>{number = 6, name = (null)}
dispatch_async(serialQueue, ^{
NSLog(@"--异步串行1: %@",[NSThread currentThread]);
dispatch_async(serialQueue, ^{
NSLog(@"--异步串行2: %@",[NSThread currentThread]);
});
});
//7. 同步串行,嵌套同一个同步串行队列(内环死锁卡崩溃)
dispatch_sync(serialQueue, ^{
NSLog(@"--同步串行1: %@",[NSThread currentThread]);
dispatch_sync(serialQueue, ^{
NSLog(@"--同步串行1: %@",[NSThread currentThread]);
});
});
//8. 同步串行,嵌套异步串行队列(外环不开启线程,内环开启线程)
//2021-05-25 21:58:05.277050+0800 GcdDemo[52128:6660403] --同步串行1: <NSThread: 0x600000a30180>{number = 1, name = main}
//2021-05-25 21:58:05.277239+0800 GcdDemo[52128:6660631] --异步串行2: <NSThread: 0x600000a65fc0>{number = 7, name = (null)}
dispatch_sync(serialQueue, ^{
NSLog(@"--同步串行1: %@",[NSThread currentThread]);
dispatch_async(serialQueue, ^{
NSLog(@"--异步串行2: %@",[NSThread currentThread]);
});
});