zl程序教程

您现在的位置是:首页 >  移动开发

当前栏目

iOS - GCD队列、任务组合

ios队列队列 任务 组合 gcd
2023-09-27 14:25:58 时间
1. 单个队列

dispatch_queue_t serialQueue dispatch_queue_create( serial , DISPATCH_QUEUE_SERIAL);

 dispatch_queue_t concurrentQueue dispatch_queue_create( concur , DISPATCH_QUEUE_CONCURRENT);

 dispatch_queue_t mainQueue dispatch_get_main_queue();

 NSLog( --主队列 % , [NSThread currentThread]);

 //1. 同步串行(不会开启新线程)

 dispatch_sync(serialQueue, ^{

 NSLog( --同步串行 % , [NSThread currentThread]);

 //2. 同步并行(不会开启新线程)

 dispatch_sync(concurrentQueue, ^{

 NSLog( --同步并行: % , [NSThread currentThread]);

 //3. 异步串行(会开启新线程)

 dispatch_async(serialQueue, ^{

 NSLog( --异步串行: % , [NSThread currentThread]);

 //4. 异步并行(会开启新线程)

 dispatch_async(concurrentQueue, ^{

 NSLog( --异步并行: % , [NSThread currentThread]);

 //5. 异步主队列(没有开启新线程)

 dispatch_async(mainQueue, ^{

 NSLog( --异步主队列: % , [NSThread currentThread]);

 //6. 主线程同步(死锁)

 dispatch_sync(mainQueue, ^{

 NSLog( --主线程同步: % , [NSThread currentThread]);

 });


2. 队列嵌套

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]);
//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]);
//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]); });



iOS开发多线程篇-GCD 上篇文章介绍了多线程是什么、线程的进程的区别,在这篇文章中,主要介绍iOS开发中多线程GCD的使用方式和注意事项,同时会给出几种多线程的案例。