iOS GCD学习

2019-07-04  本文已影响0人  3c32f188d5a4

看了两遍 iOS 多线程:『GCD』详尽总结 ,这里我手打一遍加深下映象,仅供自己加深映象使用,具体参考上面的链接

1.GCD简介

Grand Central Dispatch(GCD)是Apple开发的一个多核编程的较新的解决方法。它主要用于优化应用程序以支持多核处理器以及其他对称多处理系统。它是一个在线程池模式的基础上执行的并发任务。

为什么要用GCD呢(面试也可能问用GCD的好处)

2.GCD任务和队列

任务: 就是执行操作的意思,换句话说就是你在线程中执行的代码块。在GCD中是放在block中的。执行任务有两种方式:同步执行(sync)异步执行(async)。两者的主要区别是:是否等待队列中的任务执行结束,以及是否具备开启新线程的能力。

注意:异步执行(async) 虽然具有开启新线程的能力,但是并不一定开启新线程。这根任务所指定的队列类型有关
队列(Dispatch Queue):这里的队列指执行任务的等待队列,既用来存放任务的队列。队列是一种特殊的线性表,采用FIFO(先进先出)的原则,既新任务总是被插入到队列的末尾,而读取任务的时候总是从队列的头部开始读取。每读取一个任务,则从队列中释放一个任务。

队列(Dispatch Queue).png

在GCD中有两种队列:串行队列和并发队列。两者都符合FIFO(先进先出)的原则。两者的主要区别是:执行顺序不同,以及开启线程数不同。

注意:并发队列的并发功能只有在异步(dispatch_async)函数下才有效

image
image

3.GCD的使用步骤

GCD的使用步骤
1.创建一个队列(串行队列或并发队列)
2.将任务追加到任务的等待队列中,然后系统就会根据任务类型执行任务(同步执行或者异步执行)

3.1 队列的创建方法/获取方法

    // 串行队列创建
    dispatch_queue_t queue = dispatch_queue_create("net.ceshi.test", DISPATCH_QUEUE_SERIAL);
    // 并发队列创建方法
    dispatch_queue_t queue = dispatch_queue_create("net.ceshi.test", DISPATCH_QUEUE_CONCURRENT);

3.2 任务的创建方法

GCD提供了同步执行任务的创建方法dispatch_sync和异步执行任务创建方法dispatch_async。

// 同步执行任务创建方法
dispatch_sync(queue, ^{
    // 这里放同步执行任务代码
});
// 异步执行任务创建方法
dispatch_async(queue, ^{
    // 这里放异步执行任务代码
});

实际上刚才还说了两种特殊队列:全局并发队列、主队列。全局并发队列可以作为普通并发队列来使用。但是主队列比较特殊,所以又多了两种组合方式。这样就有六种不用的组合方式

同步执行 + 并发队列
异步执行 + 并发队列
同步执行 + 串行队列
异步执行 + 串行队列
同步执行 + 主队列
异步执行 + 主队列

区别 并发队列 串行队列 主队列
同步 没有开启新线程,串行执行任务 没有开启新线程,串行执行任务 主线程调用:死锁卡住不执行。其他线程调用:没有开启新线程,串行执行任务
异步 有开启新线程,并发执行任务 有开启新线程(1条),串行执行任务 没有开启新线程,串行执行任务

4.GCD的基本使用

4.1 同步执行+并发队列

/**
 同步执行  + 并发队列
 特点 在当前线程中执行任务不会开启新线程,任务顺序执行
 */
- (void)syncConcurrent{
    NSLog(@"currentThread---%@",[NSThread currentThread]); // 打印当前线程
    NSLog(@"asyncConcurrent---begin");
    dispatch_queue_t queue = dispatch_queue_create("net.bujige.testQueue", DISPATCH_QUEUE_CONCURRENT);
    dispatch_sync(queue, ^{
        [NSThread sleepForTimeInterval:1];              // 模拟耗时操作
        NSLog(@"1---%@",[NSThread currentThread]);      // 打印当前线程
    });
    
    dispatch_sync(queue, ^{
        // 追加任务2
        for (int i = 0; i < 2; ++i) {
            [NSThread sleepForTimeInterval:1];              // 模拟耗时操作
            NSLog(@"2---%@",[NSThread currentThread]);      // 打印当前线程
        }
    });
    NSLog(@"syncConcurrent---end");
}
/*
打印结果 
currentThread---<NSThread: 0x600001aa53c0>{number = 1, name = main}
asyncConcurrent---begin
1---<NSThread: 0x600001aa53c0>{number = 1, name = main}
2---<NSThread: 0x600001aa53c0>{number = 1, name = main}
2---<NSThread: 0x600001aa53c0>{number = 1, name = main}
syncConcurrent---end
*/

总结同步执行+并发队列:

原文 :任务按顺序执行的。按顺序执行的原因:虽然并发队列可以开启多个线程,并且同时执行多个任务。但是因为本身不能创建新线程,只有当前线程这一个线程(同步任务不具备开启新线程的能力),所以也就不存在并发。而且当前线程只有等待当前队列中正在执行的任务执行完毕之后,才能继续接着执行下面的操作(同步任务需要等待队列的任务执行结束)。所以任务只能一个接一个按顺序执行,不能同时被执行。
作者:行走少年郎
链接:https://www.jianshu.com/p/2d57c72016c6
来源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

上面这段话 我自己理解的意思是 并发队列调度任务的时候,如果是同步任务则只会在当前线程执行,并不会开启新线程。(其实并发是需要调度其他线程来执行任务的) 一个线程同一时间只能处理一个任务,所以任务只能一个个执行。

4.2 异步执行 + 并发队列

- (void)asyncConcurrent{
    NSLog(@"currentThread---%@",[NSThread currentThread]);  // 打印当前线程
    NSLog(@"asyncConcurrent---begin");
    dispatch_queue_t queue = dispatch_queue_create("net.bujige.testQueue", DISPATCH_QUEUE_CONCURRENT);
    dispatch_async(queue, ^{
        // 追加任务1
        for (int i = 0; i < 2; ++i) {
            [NSThread sleepForTimeInterval:1];              // 模拟耗时操作
            NSLog(@"1---%@",[NSThread currentThread]);      // 打印当前线程
        }
    });
    
    dispatch_async(queue, ^{
        // 追加任务1
        for (int i = 0; i < 2; ++i) {
            [NSThread sleepForTimeInterval:1];              // 模拟耗时操作
            NSLog(@"2---%@",[NSThread currentThread]);      // 打印当前线程
        }
    });
    
    NSLog(@"asyncConcurrent---end");

    /*
     打印结果
     currentThread---<NSThread: 0x6000020b2900>{number = 1, name = main}
     asyncConcurrent---begin
     asyncConcurrent---end
     1---<NSThread: 0x6000020c9bc0>{number = 3, name = (null)}
     2---<NSThread: 0x6000020e3b00>{number = 4, name = (null)}
     2---<NSThread: 0x6000020e3b00>{number = 4, name = (null)}
     1---<NSThread: 0x6000020c9bc0>{number = 3, name = (null)}
     */
}

总结异步执行+并发队列:

4.3 同步执行+串行队列

- (void)syncSerial{
    NSLog(@"currentThread---%@",[NSThread currentThread]);  // 打印当前线程
    NSLog(@"syncSerial---begin");
    
    dispatch_queue_t queue = dispatch_queue_create("net.bujige.testQueue", DISPATCH_QUEUE_SERIAL);
    dispatch_sync(queue, ^{
        // 追加任务1
        for (int i = 0; i < 2; ++i) {
            [NSThread sleepForTimeInterval:1];              // 模拟耗时操作
            NSLog(@"1---%@",[NSThread currentThread]);      // 打印当前线程
        }
    });
    dispatch_sync(queue, ^{
        // 追加任务2
        for (int i = 0; i < 2; ++i) {
            [NSThread sleepForTimeInterval:1];              // 模拟耗时操作
            NSLog(@"2---%@",[NSThread currentThread]);      // 打印当前线程
        }
    });
    NSLog(@"syncSerial---end");

    /*
  打印结果
     currentThread---<NSThread: 0x6000020b2900>{number = 1, name = main}
     syncSerial---begin
     1---<NSThread: 0x6000020b2900>{number = 1, name = main}
     1---<NSThread: 0x6000020b2900>{number = 1, name = main}
     2---<NSThread: 0x6000020b2900>{number = 1, name = main}
     2---<NSThread: 0x6000020b2900>{number = 1, name = main}
     syncSerial---end
     */
}

总结:同步执行 + 串行队列

4.4异步执行 + 串行队列

- (void)asyncSerial{
    NSLog(@"currentThread---%@",[NSThread currentThread]);  // 打印当前线程
    NSLog(@"asyncSerial---begin");
    
    dispatch_queue_t queue = dispatch_queue_create("net.bujige.testQueue", DISPATCH_QUEUE_SERIAL);
    dispatch_async(queue, ^{
        // 追加任务1
        for (int i = 0; i < 2; ++i) {
            [NSThread sleepForTimeInterval:1];              // 模拟耗时操作
            NSLog(@"1---%@",[NSThread currentThread]);      // 打印当前线程
        }
    });
    dispatch_async(queue, ^{
        // 追加任务2
        for (int i = 0; i < 2; ++i) {
            [NSThread sleepForTimeInterval:1];              // 模拟耗时操作
            NSLog(@"2---%@",[NSThread currentThread]);      // 打印当前线程
        }
    });
    NSLog(@"asyncSerial---end");
    
    /*
     currentThread---<NSThread: 0x6000020b2900>{number = 1, name = main}
     asyncSerial---begin
     asyncSerial---end
     1---<NSThread: 0x6000018dc000>{number = 3, name = (null)}
     1---<NSThread: 0x6000018dc000>{number = 3, name = (null)}
     2---<NSThread: 0x6000018dc000>{number = 3, name = (null)}
     2---<NSThread: 0x6000018dc000>{number = 3, name = (null)}
     */
}

总结:异步执行 + 串行队列

4.5 同步执行 + 主队列

4.5.1 在主线程中调用 同步执行+ 主队列

- (void)syncMain{
    NSLog(@"currentThread---%@",[NSThread currentThread]);  // 打印当前线程
    NSLog(@"syncMain---begin");
    
    dispatch_queue_t queue = dispatch_get_main_queue();
    dispatch_sync(queue, ^{
        // 追加任务1
        for (int i = 0; i < 2; ++i) {
            [NSThread sleepForTimeInterval:1];              // 模拟耗时操作
            NSLog(@"1---%@",[NSThread currentThread]);      // 打印当前线程
        }
    });
    NSLog(@"syncMain---end");
    /*
     c输出结果
     currentThread---<NSThread: 0x600003d72880>{number = 1, name = main}
     syncMain---begin
     --- 崩溃
    */
}

总结:同步执行 + 主队列

4.5.2 在其他线程中调用 同步执行 + 主队列

// 使用 NSThread 的 detachNewThreadSelector 方法会创建线程,并自动启动线程执行
 selector 任务
[NSThread detachNewThreadSelector:@selector(syncMain) toTarget:self withObject:nil];
/*
打印结果
currentThread---<NSThread: 0x600002205a80>{number = 3, name = (null)}
syncMain---begin
1---<NSThread: 0x60000226a940>{number = 1, name = main}
1---<NSThread: 0x60000226a940>{number = 1, name = main}
syncMain---end
*/

总结:在其他线程中使用同步执行 + 主队列

4.6 异步执行 + 主队列

/**
 * 异步执行 + 主队列
 * 特点:只在主线程中执行任务,执行完一个任务,再执行下一个任务
 */
- (void)asyncMain {
    NSLog(@"currentThread---%@",[NSThread currentThread]);  // 打印当前线程
    NSLog(@"asyncMain---begin");
    
    dispatch_queue_t queue = dispatch_get_main_queue();
    
    dispatch_async(queue, ^{
        // 追加任务1
        for (int i = 0; i < 2; ++i) {
            [NSThread sleepForTimeInterval:2];              // 模拟耗时操作
            NSLog(@"1---%@",[NSThread currentThread]);      // 打印当前线程
        }
    });
    
    dispatch_async(queue, ^{
        // 追加任务2
        for (int i = 0; i < 2; ++i) {
            [NSThread sleepForTimeInterval:2];              // 模拟耗时操作
            NSLog(@"2---%@",[NSThread currentThread]);      // 打印当前线程
        }
    });
    
    dispatch_async(queue, ^{
        // 追加任务3
        for (int i = 0; i < 2; ++i) {
            [NSThread sleepForTimeInterval:2];              // 模拟耗时操作
            NSLog(@"3---%@",[NSThread currentThread]);      // 打印当前线程
        }
    });
    
    NSLog(@"asyncMain---end");
/*
currentThread---<NSThread: 0x6000028d6880>{number = 1, name = main}
asyncMain---begin
asyncMain---end
1---<NSThread: 0x6000028d6880>{number = 1, name = main}
1---<NSThread: 0x6000028d6880>{number = 1, name = main}
2---<NSThread: 0x6000028d6880>{number = 1, name = main}
2---<NSThread: 0x6000028d6880>{number = 1, name = main}
3---<NSThread: 0x6000028d6880>{number = 1, name = main}
3---<NSThread: 0x6000028d6880>{number = 1, name = main}
*/
}

总结:异步执行 + 主队列

GCD线程间的通信

在iOS开发过程中,我们一般在主线程里边进行UI刷新,例如:点击、滚动、拖拽等事件。我们通常把一些耗时的操作放在其他线程,比如说图片下载、文件上传等耗时操作。而当我们有时候在其他线程完成了耗时操作时,需要回到主线程,那么就用到了线程之间的通讯。

/**
 * 线程间通信
 */
- (void)communication {
    // 获取全局并发队列
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); 
    // 获取主队列
    dispatch_queue_t mainQueue = dispatch_get_main_queue(); 
    
    dispatch_async(queue, ^{
        // 异步追加任务
        for (int i = 0; i < 2; ++i) {
            [NSThread sleepForTimeInterval:2];              // 模拟耗时操作
            NSLog(@"1---%@",[NSThread currentThread]);      // 打印当前线程
        }
        
        // 回到主线程
        dispatch_async(mainQueue, ^{
            // 追加在主线程中执行的任务
            [NSThread sleepForTimeInterval:2];              // 模拟耗时操作
            NSLog(@"2---%@",[NSThread currentThread]);      // 打印当前线程
        });
    });
}

输出结果:
2018-02-23 20:47:03.462394+0800 YSC-GCD-demo[20154:5053282] 1---<NSThread: 0x600000271940>{number = 3, name = (null)}
2018-02-23 20:47:05.465912+0800 YSC-GCD-demo[20154:5053282] 1---<NSThread: 0x600000271940>{number = 3, name = (null)}
2018-02-23 20:47:07.466657+0800 YSC-GCD-demo[20154:5052953] 2---<NSThread: 0x60000007bf80>{number = 1, name = main}
作者:行走少年郎
链接:https://www.jianshu.com/p/2d57c72016c6

6 GCD的其他方法

6.1 GCD 栅栏方法:dispatch_barrier_async

- (void)barrier{
    dispatch_queue_t queue = dispatch_queue_create("net.bujige.testQueue", DISPATCH_QUEUE_CONCURRENT);
    dispatch_async(queue, ^{
        // 追加任务1
        for (int i = 0; i < 2; ++i) {
            [NSThread sleepForTimeInterval:2];              // 模拟耗时操作
            NSLog(@"%d---%@",i,[NSThread currentThread]);      // 打印当前线程
        }
    });
    dispatch_async(queue, ^{
        // 追加任务1
        for (int i = 2; i < 4; ++i) {
            [NSThread sleepForTimeInterval:2];              // 模拟耗时操作
            NSLog(@"%d---%@",i,[NSThread currentThread]);      // 打印当前线程
        }
    });
    dispatch_barrier_async(queue, ^{
        // 追加任务 barrier
        for (int i = 0; i < 2; ++i) {
            [NSThread sleepForTimeInterval:2];              // 模拟耗时操作
            NSLog(@"barrier---%@",[NSThread currentThread]);// 打印当前线程
        }
    });
    
    dispatch_async(queue, ^{
        // 追加任务3
        for (int i = 4; i < 6; ++i) {
            [NSThread sleepForTimeInterval:2];              // 模拟耗时操作
            NSLog(@"%d---%@",i,[NSThread currentThread]);      // 打印当前线程
        }
    });
    
    dispatch_async(queue, ^{
        // 追加任务3
        for (int i = 6; i < 8; ++i) {
            [NSThread sleepForTimeInterval:2];              // 模拟耗时操作
            NSLog(@"%d---%@",i,[NSThread currentThread]);      // 打印当前线程
        }
    });
}

打印结果

2019-07-03 21:24:58.105410+0800 二叉树练习[34879:618905] 0---<NSThread: 0x600003ed4200>{number = 3, name = (null)}
2019-07-03 21:24:58.105408+0800 二叉树练习[34879:618908] 2---<NSThread: 0x600003efb5c0>{number = 4, name = (null)}
2019-07-03 21:25:00.110444+0800 二叉树练习[34879:618908] 3---<NSThread: 0x600003efb5c0>{number = 4, name = (null)}
2019-07-03 21:25:00.110444+0800 二叉树练习[34879:618905] 1---<NSThread: 0x600003ed4200>{number = 3, name = (null)}
2019-07-03 21:25:02.113756+0800 二叉树练习[34879:618905] barrier---<NSThread: 0x600003ed4200>{number = 3, name = (null)}
2019-07-03 21:25:04.118678+0800 二叉树练习[34879:618905] barrier---<NSThread: 0x600003ed4200>{number = 3, name = (null)}
2019-07-03 21:25:06.123982+0800 二叉树练习[34879:618908] 6---<NSThread: 0x600003efb5c0>{number = 4, name = (null)}
2019-07-03 21:25:06.123982+0800 二叉树练习[34879:618905] 4---<NSThread: 0x600003ed4200>{number = 3, name = (null)}
2019-07-03 21:25:08.128269+0800 二叉树练习[34879:618905] 5---<NSThread: 0x600003ed4200>{number = 3, name = (null)}
2019-07-03 21:25:08.128295+0800 二叉树练习[34879:618908] 7---<NSThread: 0x600003efb5c0>{number = 4, name = (null)}

6.2 GCD 延时执行方法:dispatch_after (常用的不抄了)

6.3 GCD 一次性代码(只执行一次):dispatch_once (常用的不抄了)

6.4 GCD 快速迭代方法:dispatch_apply

/**
 * 快速迭代方法 dispatch_apply
 */
- (void)apply {
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    NSLog(@"apply---begin");
    dispatch_apply(6, queue, ^(size_t index) {
        NSLog(@"%zd---%@",index, [NSThread currentThread]);
    });
    NSLog(@"apply---end");
}

因为是在并发队列中异步执行任务,所以各个任务的执行时间长短不定,最后结束顺序也不定。但是apply---end一定在最后执行。这是因为dispatch_apply函数会等待全部任务执行完毕。

6.5 GCD队列组:dispatch_group

有时候我们会有这样的需求:分别异步执行2个耗时任务,然后当2个耗时任务都执行完毕后再回到主线程执行任务。这时候我们可以用到GCD的队列组。

6.5.1 dispatch_group_notify

- (void)groupNotify{
    NSLog(@"currentThread---%@",[NSThread currentThread]);  // 打印当前线程
    NSLog(@"group---begin");
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // 追加任务1
        for (int i = 0; i < 2; ++i) {
            [NSThread sleepForTimeInterval:2];              // 模拟耗时操作
            NSLog(@"1---%@",[NSThread currentThread]);      // 打印当前线程
        }
    });
    dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // 追加任务1
        for (int i = 0; i < 2; ++i) {
            [NSThread sleepForTimeInterval:2];              // 模拟耗时操作
            NSLog(@"2---%@",[NSThread currentThread]);      // 打印当前线程
        }
    });
    
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        // 等前面的异步任务1、任务2都执行完毕后,回到主线程执行下边任务
        for (int i = 0; i < 2; ++i) {
            [NSThread sleepForTimeInterval:2];              // 模拟耗时操作
            NSLog(@"3---%@",[NSThread currentThread]);      // 打印当前线程
        }
        NSLog(@"group---end");
    });
}
/* 
打印结果
currentThread---<NSThread: 0x600002722940>{number = 1, name = main}
group---begin
2---<NSThread: 0x600002750bc0>{number = 4, name = (null)}
1---<NSThread: 0x600002758980>{number = 3, name = (null)}
1---<NSThread: 0x600002758980>{number = 3, name = (null)}
2---<NSThread: 0x600002750bc0>{number = 4, name = (null)}
3---<NSThread: 0x600002722940>{number = 1, name = main}
3---<NSThread: 0x600002722940>{number = 1, name = main}
group---end
*/

总结:当所有队列组中的任务完成之后,才执行dispatch_group_notify block中的任务。

6.5.2 dispatch_group_wait

6.5.3 dispatch_group_enter、dispatch_group_leave

原文

/**
 * 队列组 dispatch_group_enter、dispatch_group_leave
 */
- (void)groupEnterAndLeave
{
    NSLog(@"currentThread---%@",[NSThread currentThread]);  // 打印当前线程
    NSLog(@"group---begin");
    
    dispatch_group_t group = dispatch_group_create();
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_group_enter(group);
    dispatch_async(queue, ^{
        // 追加任务1
        for (int i = 0; i < 2; ++i) {
            [NSThread sleepForTimeInterval:2];              // 模拟耗时操作
            NSLog(@"1---%@",[NSThread currentThread]);      // 打印当前线程
        }
        dispatch_group_leave(group);
    });
    
    dispatch_group_enter(group);
    dispatch_async(queue, ^{
        // 追加任务2
        for (int i = 0; i < 2; ++i) {
            [NSThread sleepForTimeInterval:2];              // 模拟耗时操作
            NSLog(@"2---%@",[NSThread currentThread]);      // 打印当前线程
        }
        dispatch_group_leave(group);
    });
    
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        // 等前面的异步操作都执行完毕后,回到主线程.
        for (int i = 0; i < 2; ++i) {
            [NSThread sleepForTimeInterval:2];              // 模拟耗时操作
            NSLog(@"3---%@",[NSThread currentThread]);      // 打印当前线程
        }
        NSLog(@"group---end");
    });
    
//    // 等待上面的任务全部完成后,会往下继续执行(会阻塞当前线程)
//    dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
//
//    NSLog(@"group---end");
}

输出结果:
2018-02-23 22:14:17.997667+0800 YSC-GCD-demo[20592:5214830] currentThread---<NSThread: 0x604000066600>{number = 1, name = main}
2018-02-23 22:14:17.997839+0800 YSC-GCD-demo[20592:5214830] group---begin
2018-02-23 22:14:20.000298+0800 YSC-GCD-demo[20592:5215094] 1---<NSThread: 0x600000277c80>{number = 4, name = (null)}
2018-02-23 22:14:20.000305+0800 YSC-GCD-demo[20592:5215095] 2---<NSThread: 0x600000277c40>{number = 3, name = (null)}
2018-02-23 22:14:22.001323+0800 YSC-GCD-demo[20592:5215094] 1---<NSThread: 0x600000277c80>{number = 4, name = (null)}
2018-02-23 22:14:22.001339+0800 YSC-GCD-demo[20592:5215095] 2---<NSThread: 0x600000277c40>{number = 3, name = (null)}
2018-02-23 22:14:24.002321+0800 YSC-GCD-demo[20592:5214830] 3---<NSThread: 0x604000066600>{number = 1, name = main}
2018-02-23 22:14:26.002852+0800 YSC-GCD-demo[20592:5214830] 3---<NSThread: 0x604000066600>{number = 1, name = main}
2018-02-23 22:14:26.003116+0800 YSC-GCD-demo[20592:5214830] group---end

从dispatch_group_enter、dispatch_group_leave相关代码运行结果中可以看出:当所有任务执行完成之后,才执行 dispatch_group_notify 中的任务。这里的dispatch_group_enter、dispatch_group_leave组合,其实等同于dispatch_group_async。

我们自己在用队列组的情况通常是 发起多个异步的网络请求,等请求全部完成后刷新UI,这个时候为了效率 保证等多个异步请求完成后再刷新UI 经常会用dispatch_group_enter、dispatch_group_leave组合,如果只用dispatch_group_async则达不到这种效果。

/*
如果去掉ispatch_group_enter、dispatch_group_leave组合,则dispatch_group_async就不好使了。
*/
- (void)groupNotify{
    NSLog(@"currentThread---%@",[NSThread currentThread]);  // 打印当前线程
    NSLog(@"group---begin");
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_enter(group);
    dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // 追加任务1
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            for (int i = 0; i < 2; ++i) {
                [NSThread sleepForTimeInterval:2];              // 模拟耗时操作
                NSLog(@"1---%@",[NSThread currentThread]);      // 打印当前线程
            }
            dispatch_group_leave(group);

        });
      
    });
    
    dispatch_group_enter(group);
    dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // 追加任务2
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            for (int i = 0; i < 2; ++i) {
                [NSThread sleepForTimeInterval:2];              // 模拟耗时操作
                NSLog(@"2---%@",[NSThread currentThread]);      // 打印当前线程
            }
            dispatch_group_leave(group);

        });
    });
    
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        // 等前面的异步任务1、任务2都执行完毕后,回到主线程执行下边任务
        for (int i = 0; i < 2; ++i) {
            [NSThread sleepForTimeInterval:2];              // 模拟耗时操作
            NSLog(@"3---%@",[NSThread currentThread]);      // 打印当前线程
        }
        NSLog(@"group---end");
    });
}

6.6 GCD 信号量:dispatch_semaphore

GCD中的信号量是指dispatch semaphore 是持有计数的信号。类似于过高速路收费站的栏杆。可以通过时,打开栏杆,不可以通过时,关闭栏杆。在dispatch semaphore 中,使用计数来完成这个功能,计数小于0时等待,不可通过。计数为0或大于0时,计数减1且不等待,可通过。
dispatch_semaphore 提供了三个函数。

dispatch_semaphore_wait
// 等待降低信号量,接收一个信号和时间值(多为DISPATCH_TIME_FOREVER)
// 若信号的信号量为0,则会阻塞当前线程,直到信号量大于0或者经过输入的时间值;
// 若信号量大于0,则会使信号量减1并返回,程序继续住下执行

信号量的使用前提是:想清楚你需要处理哪个线程等待(阻塞),又要哪个线程继续执行,然后使用信号量。
Dispatch Semaphore 在实际开发中主要用于:

6.6.1 Dispatch Semaphore 线程同步

我们在开发中会遇到这样的需求:异步执行耗时任务,并使用异步执行的结果进行一些额外的操作。换句话说,相当于,将异步执行任务转换为同步执行任务。比如说:AFNetworking 中 AFURLSessionManager.m 里面的 tasksForKeyPath: 方法。通过引入信号量的方式,等待异步执行任务结果,获取到 tasks,然后再返回该 tasks

- (NSArray *)tasksForKeyPath:(NSString *)keyPath {
    __block NSArray *tasks = nil;
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    [self.session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
        if ([keyPath isEqualToString:NSStringFromSelector(@selector(dataTasks))]) {
            tasks = dataTasks;
        } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(uploadTasks))]) {
            tasks = uploadTasks;
        } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(downloadTasks))]) {
            tasks = downloadTasks;
        } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(tasks))]) {
            tasks = [@[dataTasks, uploadTasks, downloadTasks] valueForKeyPath:@"@unionOfArrays.self"];
        }

        dispatch_semaphore_signal(semaphore);
    }];

    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);

    return tasks;
}

下面我们来利用Dispatch Semaphore 实现线程同步,将异步执行任务转换为同步执行任务。

- (void)semaphoreSync{
    NSLog(@"currentThread---%@",[NSThread currentThread]);  // 打印当前线程
    NSLog(@"semaphore---begin");
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    __block int number = 0;
    dispatch_async(queue, ^{
        [NSThread sleepForTimeInterval:2];
        NSLog(@"1---%@",[NSThread currentThread]);      // 打印当前线程
        
        number = 100;
        
        dispatch_semaphore_signal(semaphore);
    });
    NSLog(@"semaphore--number = %d",number);
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    NSLog(@"semaphore---end,number = %d",number);
 /*
  打印结果:
currentThread---<NSThread: 0x600002452940>{number = 1, name = main}
semaphore---begin
semaphore---end,number = 0
1---<NSThread: 0x600002434f40>{number = 3, name = (null)}
semaphore---end,number = 100
*/
}

总结:

  1. semaphore 初始创建时计数为 0。
    2.异步执行将任务 1 追加到队列之后,不做等待,接着执行
    3.打印 semaphore---end,number = 0
    4.dispatch_semaphore_wait方法,semaphore 减 1,此时 semaphore == -1,当前线程进入等待状态。
    5.然后,异步任务 1 开始执行。任务1执行到dispatch_semaphore_signal之后,总信号量加1,此时 semaphore == 0,正在被阻塞的线程(主线程)恢复继续执行。
    6.最后打印semaphore---end,number = 100

这样就实现了线程同步,将异步执行任务转换为同步执行任务。

6.6.2 Dispatch Semaphore 线程安全和线程同步(为线程加锁)

线程安全: 如果你的代码所在的进程中有多个线程在同时运行,而这些线程可能会同时运行这段代码。如果每次运行结果和单线程运行的结果是一样的,而且其他的变量的值也和预期是一样的,就是线程安全的。
若每个线程中对全局变量。静态变量只有读操作,而无写操作,一般来说这个全局变量是线程安全的。若有多个线程通知执行写操作(更改变量),一般都需要考虑线程同步,否则的话就可能影响线程安全。
线程同步:可理解为线程A和线程B一块配合,A执行到一定程度时 要依靠线程B的某个结果,于是停下来,示意B运行,B去执行,再将接活给A,A继续执行。

模拟火车票售卖,实现线程安全和解决线程同步问题。

6.6.2.1 非线程安全(不使用semaphore)

先看看不考虑线程安全的代码:

/**
 * 非线程安全:不使用 semaphore
 * 初始化火车票数量、卖票窗口(非线程安全)、并开始卖票
 */
- (void)initTicketStatusNotSave {
    NSLog(@"currentThread---%@",[NSThread currentThread]);  // 打印当前线程
    NSLog(@"semaphore---begin");
    
    self.ticketSurplusCount = 50;
    
    // queue1 代表北京火车票售卖窗口
    dispatch_queue_t queue1 = dispatch_queue_create("net.bujige.testQueue1", DISPATCH_QUEUE_SERIAL);
    // queue2 代表上海火车票售卖窗口
    dispatch_queue_t queue2 = dispatch_queue_create("net.bujige.testQueue2", DISPATCH_QUEUE_SERIAL);
    
    __weak typeof(self) weakSelf = self;
    dispatch_async(queue1, ^{
        [weakSelf saleTicketNotSafe];
    });
    
    dispatch_async(queue2, ^{
        [weakSelf saleTicketNotSafe];
    });
}

/**
 * 售卖火车票(非线程安全)
 */
- (void)saleTicketNotSafe {
    while (1) {
        
        if (self.ticketSurplusCount > 0) {  //如果还有票,继续售卖
            self.ticketSurplusCount--;
            NSLog(@"%@", [NSString stringWithFormat:@"剩余票数:%d 窗口:%@", self.ticketSurplusCount, [NSThread currentThread]]);
            [NSThread sleepForTimeInterval:0.2];
        } else { //如果已卖完,关闭售票窗口
            NSLog(@"所有火车票均已售完");
            break;
        }
        
    }
}

打印结果
剩余票数:8 窗口:<NSThread: 0x6000002b7040>{number = 4, name = (null)}
剩余票数:8 窗口:<NSThread: 0x600000295c40>{number = 3, name = (null)}
剩余票数:7 窗口:<NSThread: 0x6000002b7040>{number = 4, name = (null)}
剩余票数:6 窗口:<NSThread: 0x600000295c40>{number = 3, name = (null)}
剩余票数:4 窗口:<NSThread: 0x6000002b7040>{number = 4, name = (null)}
剩余票数:5 窗口:<NSThread: 0x600000295c40>{number = 3, name = (null)}

- (void)saleTicketSafe{
    while (1) {
        // 相当于加锁
        // 原始信号量值为1  dispatch_semaphore_wait后减一 此时值为0  继续往下执行
        dispatch_semaphore_wait(semaphoreLock, DISPATCH_TIME_FOREVER);
        if (self.ticketSurplusCount > 0) {  //如果还有票,继续售卖
            self.ticketSurplusCount--;
            NSLog(@"%@", [NSString stringWithFormat:@"剩余票数:%ld 窗口:%@", self.ticketSurplusCount, [NSThread currentThread]]);
            [NSThread sleepForTimeInterval:0.2];
        } else { //如果已卖完,关闭售票窗口
            NSLog(@"所有火车票均已售完");
            // 相当于解锁
            // 当前信号量值为0  dispatch_semaphore_signal后值加1 此时值为1  继续往下执行
            dispatch_semaphore_signal(semaphoreLock);
            break;
        }
        // 相当于解锁
        // 当前信号量值为0  dispatch_semaphore_signal后值加1 此时值为1  继续往下执行
        dispatch_semaphore_signal(semaphoreLock);
    }
}

打印结果
剩余票数:4 窗口:<NSThread: 0x600001afb440>{number = 4, name = (null)}
剩余票数:3 窗口:<NSThread: 0x600001acc440>{number = 3, name = (null)}
剩余票数:2 窗口:<NSThread: 0x600001afb440>{number = 4, name = (null)}
剩余票数:1 窗口:<NSThread: 0x600001acc440>{number = 3, name = (null)}
剩余票数:0 窗口:<NSThread: 0x600001afb440>{number = 4, name = (null)}
所有火车票均已售完

最后重申一遍 此篇文章是对着iOS 多线程:『GCD』详尽总结 此文抄的,勿喷。给自己加深映像用。具体请看上面的链接。 特别感谢 行走少年郎 的文章

上一篇 下一篇

猜你喜欢

热点阅读