从dispatch_group_enter、dispatch_group_leave
相关代码运行结果中可以看出:当所有任务执行完成之后,才执行 dispatch_group_notify 中的任务。这里的dispatch_group_enter、dispatch_group_leave
组合,其实等同于dispatch_group_async
。
6.6 GCD 信号量:dispatch_semaphore
GCD 中的信号量是指 Dispatch Semaphore,是持有计数的信号。类似于过高速路收费站的栏杆。可以通过时,打开栏杆,不可以通过时,关闭栏杆。在 Dispatch Semaphore 中,使用计数来完成这个功能,计数为0时等待,不可通过。计数为1或大于1时,计数减1且不等待,可通过。
Dispatch Semaphore 提供了三个函数。
-
dispatch_semaphore_create
:创建一个Semaphore并初始化信号的总量
-
dispatch_semaphore_signal
:发送一个信号,让信号总量加1
-
dispatch_semaphore_wait
:可以使总信号量减1,当信号总量为0时就会一直等待(阻塞所在线程),否则就可以正常执行。
注意:信号量的使用前提是:想清楚你需要处理哪个线程等待(阻塞),又要哪个线程继续执行,然后使用信号量。
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 实现线程同步,将异步执行任务转换为同步执行任务。
- /**
- * 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, ^{
- // 追加任务1
- [NSThread sleepForTimeInterval:2]; // 模拟耗时操作
- NSLog(@"1---%@",[NSThread currentThread]); // 打印当前线程
-
- number = 100;
-
- dispatch_semaphore_signal(semaphore);
- });
-
- dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
- NSLog(@"semaphore---end,number = %zd",number);
- }
输出结果:
2018-02-23 22:22:26.521665+0800 YSC-GCD-demo[20642:5246341] currentThread---<NSThread: 0x60400006bc80>{number = 1, name = main}
2018-02-23 22:22:26.521869+0800 YSC-GCD-demo[20642:5246341] semaphore---begin
2018-02-23 22:22:28.526841+0800 YSC-GCD-demo[20642:5246638] 1---<NSThread: 0x600000272300>{number = 3, name = (null)}
2018-02-23 22:22:28.527030+0800 YSC-GCD-demo[20642:5246341] semaphore---end,number = 100
从 Dispatch Semaphore 实现线程同步的代码可以看到:
-
semaphore---end
是在执行完 number = 100;
之后才打印的。而且输出结果 number 为 100。
这是因为异步执行
不会做任何等待,可以继续执行任务。异步执行
将任务1追加到队列之后,不做等待,接着执行dispatch_semaphore_wait
方法。此时 semaphore == 0,当前线程进入等待状态。然后,异步任务1开始执行。任务1执行到dispatch_semaphore_signal
之后,总信号量,此时 semaphore == 1,dispatch_semaphore_wait
方法使总信号量减1,正在被阻塞的线程(主线程)恢复继续执行。最后打印semaphore---end,number = 100
。这样就实现了线程同步,将异步执行任务转换为同步执行任务。
6.6.2 Dispatch Semaphore 线程安全和线程同步(为线程加锁)
线程安全:如果你的代码所在的进程中有多个线程在同时运行,而这些线程可能会同时运行这段代码。如果每次运行结果和单线程运行的结果是一样的,而且其他的变量的值也和预期的是一样的,就是线程安全的。
若每个线程中对全局变量、静态变量只有读操作,而无写操作,一般来说,这个全局变量是线程安全的;若有多个线程同时执行写操作(更改变量),一般都需要考虑线程同步,否则的话就可能影响线程安全。
线程同步:可理解为线程 A 和 线程 B 一块配合,A 执行到一定程度时要依靠线程 B 的某个结果,于是停下来,示意 B 运行;B 依言执行,再将结果给 A;A 再继续操作。
举个简单例子就是:两个人在一起聊天。两个人不能同时说话,避免听不清(操作冲突)。等一个人说完(一个线程结束操作),另一个再说(另一个线程再开始操作)。
下面,我们模拟火车票售卖的方式,实现 NSThread 线程安全和解决线程同步问题。
场景:总共有50张火车票,有两个售卖火车票的窗口,一个是北京火车票售卖窗口,另一个是上海火车票售卖窗口。两个窗口同时售卖火车票,卖完为止。
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;
- }
- }
- }
输出结果(部分):
2018-02-23 22:25:35.789072+0800 YSC-GCD-demo[20712:5258914] currentThread---<NSThread: 0x604000068880>{number = 1, name = main}
2018-02-23 22:25:35.789260+0800 YSC-GCD-demo[20712:5258914] semaphore---begin
2018-02-23 22:25:35.789641+0800 YSC-GCD-demo[20712:5259176] 剩余票数:48 窗口:<NSThread: 0x60000027db80>{number = 3, name = (null)}
2018-02-23 22:25:35.789646+0800 YSC-GCD-demo[20712:5259175] 剩余票数:49 窗口:<NSThread: 0x60000027e740>{number = 4, name = (null)}
2018-02-23 22:25:35.994113+0800 YSC-GCD-demo[20712:5259175] 剩余票数:47 窗口:<NSThread: 0x60000027e740>{number = 4, name = (null)}
2018-02-23 22:25:35.994129+0800 YSC-GCD-demo[20712:5259176] 剩余票数:46 窗口:<NSThread: 0x60000027db80>{number = 3, name = (null)}
2018-02-23 22:25:36.198993+0800 YSC-GCD-demo[20712:5259176] 剩余票数:45 窗口:<NSThread: 0x60000027db80>{number = 3, name = (null)}
...
可以看到在不考虑线程安全,不使用 semaphore 的情况下,得到票数是错乱的,这样显然不符合我们的需求,所以我们需要考虑线程安全问题。
6.6.2.2 线程安全(使用 semaphore 加锁)
考虑线程安全的代码:
- /**
- * 线程安全:使用 semaphore 加锁
- * 初始化火车票数量、卖票窗口(线程安全)、并开始卖票
- */
- - (void)initTicketStatusSave {
- NSLog(@"currentThread---%@",[NSThread currentThread]); // 打印当前线程
- NSLog(@"semaphore---begin");
-
- semaphoreLock = dispatch_semaphore_create(1);
-
- 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 saleTicketSafe];
- });
-
- dispatch_async(queue2, ^{
- [weakSelf saleTicketSafe];
- });
- }
- /**
- * 售卖火车票(线程安全)
- */
- - (void)saleTicketSafe {
- while (1) {
- // 相当于加锁
- dispatch_semaphore_wait(semaphoreLock, DISPATCH_TIME_FOREVER);
-
- if (self.ticketSurplusCount > 0) { //如果还有票,继续售卖
- self.ticketSurplusCount--;
- NSLog(@"%@", [NSString stringWithFormat:@"剩余票数:%d 窗口:%@", self.ticketSurplusCount, [NSThread currentThread]]);
- [NSThread sleepForTimeInterval:0.2];
- } else { //如果已卖完,关闭售票窗口
- NSLog(@"所有火车票均已售完");
-
- // 相当于解锁
- dispatch_semaphore_signal(semaphoreLock);
- break;
- }
-
- // 相当于解锁
- dispatch_semaphore_signal(semaphoreLock);
- }
- }
输出结果为:
2018-02-23 22:32:19.814232+0800 YSC-GCD-demo[20862:5290531] currentThread---<NSThread: 0x6000000783c0>{number = 1, name = main}
2018-02-23 22:32:19.814412+0800 YSC-GCD-demo[20862:5290531] semaphore---begin
2018-02-23 22:32:19.814837+0800 YSC-GCD-demo[20862:5290687] 剩余票数:49 窗口:<NSThread: 0x6040002709c0>{number = 3, name = (null)}
2018-02-23 22:32:20.017745+0800 YSC-GCD-demo[20862:5290689] 剩余票数:48 窗口:<NSThread: 0x60000046c640>{number = 4, name = (null)}
2018-02-23 22:32:20.222039+0800 YSC-GCD-demo[20862:5290687] 剩余票数:47 窗口:<NSThread: 0x6040002709c0>{number = 3, name = (null)}
...
2018-02-23 22:32:29.024817+0800 YSC-GCD-demo[20862:5290689] 剩余票数:4 窗口:<NSThread: 0x60000046c640>{number = 4, name = (null)}
2018-02-23 22:32:29.230110+0800 YSC-GCD-demo[20862:5290687] 剩余票数:3 窗口:<NSThread: 0x6040002709c0>{number = 3, name = (null)}
2018-02-23 22:32:29.433615+0800 YSC-GCD-demo[20862:5290689] 剩余票数:2 窗口:<NSThread: 0x60000046c640>{number = 4, name = (null)}
2018-02-23 22:32:29.637572+0800 YSC-GCD-demo[20862:5290687] 剩余票数:1 窗口:<NSThread: 0x6040002709c0>{number = 3, name = (null)}
2018-02-23 22:32:29.840234+0800 YSC-GCD-demo[20862:5290689] 剩余票数:0 窗口:<NSThread: 0x60000046c640>{number = 4, name = (null)}
2018-02-23 22:32:30.044960+0800 YSC-GCD-demo[20862:5290687] 所有火车票均已售完
2018-02-23 22:32:30.045260+0800 YSC-GCD-demo[20862:5290689] 所有火车票均已售完
可以看出,在考虑了线程安全的情况下,使用
dispatch_semaphore
机制之后,得到的票数是正确的,没有出现混乱的情况。我们也就解决了多个线程同步的问题。
作者:行走少年郎
链接:https://www.jianshu.com/p/2d57c72016c6
來源:简书