GCD中的dispatch_sync、dispatch_sync 分别与串行、并行队列组合执行小实验
平常开发中会经常用gcd做一下多线程任务,但一直没有对同步、异步任务在串行、并行队列的执行情况做个全面的认识,今天写了个demo跑了下,还是有些新发现的。
代码如下:
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[self gcdTest];
}
-(void)gcdTest
{
dispatch_queue_t serialQueue= dispatch_queue_create("串行队列", DISPATCH_QUEUE_SERIAL);
dispatch_queue_t concurrentQueue=dispatch_queue_create("并行队列", DISPATCH_QUEUE_CONCURRENT);
dispatch_queue_t mainQueue=dispatch_get_main_queue();
dispatch_queue_t globalQueue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//1:
// for(int i=0;i<10;i++){
// dispatch_sync(serialQueue, ^{
// NSLog(@"任务执行中....-%d\n mainThread:%@",i,[NSThread currentThread]);
// });
// }
//结果,同步任务在串行队列中,在主线程下串行执行
//2:
// for(int i=0;i<10;i++){
// dispatch_sync(concurrentQueue, ^{
// NSLog(@"任务执行中....-%d\n mainThread:%@",i,[NSThread currentThread]);
// });
// }
//结果,同步任务在并行队列中,在主线程下串行执行
//3:
// for(int i=0;i<10;i++){
// dispatch_sync(mainQueue, ^{
// NSLog(@"任务执行中....-%d\n mainThread:%@",i,[NSThread currentThread]);
// });
// }
//结果,同步任务在主队列中,锁死
//4:
// for(int i=0;i<10;i++){
// dispatch_sync(globalQueue, ^{
// NSLog(@"任务执行中....-%d\n mainThread:%@",i,[NSThread currentThread]);
// });
// }
//结果,同步任务在全局队列中,在主线程下串行执行
//5:
// for(int i=0;i<10;i++){
// dispatch_async(serialQueue, ^{
// NSLog(@"任务执行中....-%d\n mainThread:%@",i,[NSThread currentThread]);
// });
// }
//结果,异步任务在串行队列中,在一个子线程中串行执行
//6:
// for(int i=0;i<10;i++){
// dispatch_async(concurrentQueue, ^{
// NSLog(@"任务执行中....-%d\n mainThread:%@",i,[NSThread currentThread]);
// });
// }
//结果,异步任务在并行队列中,在多个子线程中并行执行
//7:
// for(int i=0;i<10;i++){
// dispatch_async(mainQueue, ^{
// NSLog(@"任务执行中....-%d\n mainThread:%@",i,[NSThread currentThread]);
// });
// }
//结果,异步任务在主队列中,在主线程中串行执行
//8:
for(int i=0;i<10;i++){
dispatch_async(globalQueue, ^{
NSLog(@"任务执行中....-%d\n mainThread:%@",i,[NSThread currentThread]);
});
}
//结果,异步任务在全局队列中,在多个子线程中并行执行
}
总结如下:
dispatch_sync:同步任务无论在自定义串行队列、自定义并行队列、主队列(当前线程为主线程时会出现死锁)、全局队列 执行任务时,都不会创建子线程,而是在当前线程中串行执行;
dispatch_async:异步任务无论在自定义串行队列、自定义并行队列(主队列除外,主队列下,任务会在主线中串行执行)、全局队列 执行任务时,都会创建子线程,并且在子线程中执行;
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· 分享4款.NET开源、免费、实用的商城系统
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了