关于gcd中串行队列并行队列,以及同步任务和异步任务的花式嵌套,分析执行结果
多线程调试常用代码:
[NSThread sleepForTimeInterval:3.0f]; //模拟耗时操作
[NSThread currentThread]; //%@打印当前线程序号,主线程师1,一次递增。
gcd的任务
同步任务: dispatch_sync(queue, ^{});
- 最大的作用是阻塞并行队列的非嵌套异步任务执行。只有当前的同步任务执行完成,才会执行后面的同步/异步任务。
- (void)demo01 {
//该代码下方嵌套同步任务一定先用嵌套异步任务执行
dispatch_queue_t concurrent = dispatch_queue_create("com.gcd.example", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(concurrent, ^{
//跑线程2
NSLog(@"异步任务000 %@", [NSThread currentThread]);
//同步任务
dispatch_sync(concurrent, ^{
//跑线程2
NSLog(@"嵌套同步任务 %@", [NSThread currentThread]);
//模拟耗时操作
[NSThread sleepForTimeInterval:3];
});
//异步任务
dispatch_async(concurrent, ^{
//跑线程2/3/...
NSLog(@"嵌套异步任务111 %@", [NSThread currentThread]);
});
//异步任务
dispatch_async(concurrent, ^{
//跑线程2/3/...
NSLog(@"嵌套异步任务222 %@", [NSThread currentThread]);
});
//异步任务
dispatch_async(concurrent, ^{
//跑线程2/3/...
NSLog(@"嵌套异步任务333 %@", [NSThread currentThread]);
});
//异步任务
dispatch_async(concurrent, ^{
//跑线程2/3/...
NSLog(@"嵌套异步任务444 %@", [NSThread currentThread]);
});
});
}
//执行结果:
多线程篇[13337:19767072] 异步任务000 <NSThread: 0x600001776c00>{
number = 2, name = (null)}
多线程篇[13337:19767072] 嵌套同步任务 <NSThread: 0x600001776c00>{
number = 2, name = (null)}
多线程篇[13337:19767072] 嵌套异步任务222 <NSThread: 0x600001776c00>{
number = 2, name = (null)}
多线程篇[13337:19767075] 嵌套异步任务111 <NSThread: 0x60000179e500>{
number = 3, name = (null)}
多线程篇[13337:19767085] 嵌套异步任务333 <NSThread: 0x60000179e7c0>{
number = 5, name = (null)}
多线程篇[13337:19767087] 嵌套异步任务444 <NSThread: 0x6000017a4940>{
number = 4, name = (null)}
- 不会开启新的线程,在当前线程执行任务
- 在主线程中会阻塞当前任务(原因:主线程runLoop一直在执行中,再次添加任务互相等待,导致阻塞)不会执行后续代码
- (void)demo02 {
//主队列同步任务阻塞
dispatch_queue_t mainQueue = dispatch_get_main_queue();
dispatch_sync(mainQueue, ^{
NSLog(@"同步任务%@", [NSThread currentThread]); //阻塞
});
NSLog(@"当前任务%@", [NSThread currentThread]); //阻塞