美文网首页
iOS中GCD的使用

iOS中GCD的使用

作者: 嗨哒哥 | 来源:发表于2018-07-18 17:17 被阅读0次

    在前一篇中介绍了NSThread的使用 ,接下来我们将介绍GCD的使用

    GCD简介

    GCD的全称是Grand Central Dispatch,翻译过来就是重要的中枢调度器,是一个纯C语言的多线程工具,GCD是苹果公司为了充分利用多核的并行运算而提供的一套高级API,并且不需要程序员手动的去管理线程的生命周期,是不是很厉害!!!!

    同步线程和异步线程

    同步只能在当前线程中执行,不具备开启线程的能力
    异步可在新的线程中执行任务,具备开启线程的能力
    同步和异步只影响能不能开启多线程
    同步和异步线程的创建方式

    创建同步线程:dispatch_sync(dispatch_queue_t , block);
    创建异步线程dispatch_async(dispatch_queue_t , block);
    

    并发队列和串行队列

    并发队列,可以让多个任务同时执行,自动开启多个线程执行任务;并且并发任务只能在异步的时候才有效
    串行队列,任务一个接着一个的执行,也就是说当期任务执行完成之后才开始下一个任务的执行
    并发和串行只影响多个任务能不能同时执行

    创建并行队列:
        //队列优先级
        //#define DISPATCH_QUEUE_PRIORITY_HIGH 2
        //#define DISPATCH_QUEUE_PRIORITY_DEFAULT 0
        //#define DISPATCH_QUEUE_PRIORITY_LOW (-2)
        //#define DISPATCH_QUEUE_PRIORITY_BACKGROUND INT16_MIN
        dispatch_queue_t queue = dispatch_queue_create("DISPATCH_QUEUE", DISPATCH_QUEUE_CONCURRENT);
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    创建串行队列:
    dispatch_queue_t queue = dispatch_queue_create("DISPATCH_QUEUE", DISPATCH_QUEUE_SERIAL);
    关于dispatch_queue_create的第二个参数解释
    In macOS 10.7 and later or iOS 4.3 and later, specify [DISPATCH_QUEUE_SERIAL](apple-reference-documentation://hcZN500E9U) (or `NULL`) to create a serial queue or specify [DISPATCH_QUEUE_CONCURRENT](apple-reference-documentation://hcOkfZQpaV) to create a concurrent queue. In earlier versions, you must specify `NULL`for this parameter.
    
    

    队列和线程的结合使用

    队列分为两种:串行队列和并行队列
    线程也分为两种:同步线程和异步线程

    把队列和线程结合起来可以产生4中组合方式:

    方式1、并行异步队列
    方式2、串行异步队列
    方式3、并行同步队列
    方式4、串行同步队列
    

    异步串行队列的创建

    /**
     创建异步串行队列,会开辟新的线程,执行方式是按照顺序依次执行
     */
    - (void)createAsyncSerialThread {
    //    DISPATCH_QUEUE_CONCURRENT并行队列
    //    DISPATCH_QUEUE_SERIAL串行队列
        dispatch_queue_t queue = dispatch_queue_create("DISPATCH_QUEUE", DISPATCH_QUEUE_SERIAL);
        dispatch_async(queue, ^{
            NSLog(@"----------GCD1----%@", [NSThread currentThread]);
        });
        dispatch_async(queue, ^{
            NSLog(@"----------GCD2----%@", [NSThread currentThread]);
        });
        dispatch_async(queue, ^{
            NSLog(@"----------GCD3----%@", [NSThread currentThread]);
        });
        dispatch_async(queue, ^{
            NSLog(@"----------GCD4----%@", [NSThread currentThread]);
        });
    }
    

    异步串行队列执行后的打印信息如下:

    ThreadDemo[8599:11573279] ----------GCD1----<NSThread: 0x604000466080>{number = 3, name = (null)}
    ThreadDemo[8599:11573279] ----------GCD2----<NSThread: 0x604000466080>{number = 3, name = (null)}
    ThreadDemo[8599:11573279] ----------GCD3----<NSThread: 0x604000466080>{number = 3, name = (null)}
    ThreadDemo[8599:11573279] ----------GCD4----<NSThread: 0x604000466080>{number = 3, name = (null)}
    

    从上面的打印信息可以看到,线程队列是一个一个按照循序往下执行,每个线程的执行都是在同一条线程里,并没有开辟多条线程
    异步并行队列的创建

    /**
     创建异步并行队列,会创建新的线程执行任务,执行任务的顺序随机
     */
    - (void)createAsyncConcurrentThread {
        //队列优先级
        //#define DISPATCH_QUEUE_PRIORITY_HIGH 2
        //#define DISPATCH_QUEUE_PRIORITY_DEFAULT 0
        //#define DISPATCH_QUEUE_PRIORITY_LOW (-2)
        //#define DISPATCH_QUEUE_PRIORITY_BACKGROUND INT16_MIN
        
        //    DISPATCH_QUEUE_CONCURRENT并行队列
        dispatch_queue_t queue = dispatch_queue_create("DISPATCH_QUEUE", DISPATCH_QUEUE_CONCURRENT);
        //    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_async(queue, ^{
            NSLog(@"----------GCD1----%@", [NSThread currentThread]);
        });
        dispatch_async(queue, ^{
            NSLog(@"----------GCD2----%@", [NSThread currentThread]);
        });
        dispatch_async(queue, ^{
            NSLog(@"----------GCD3----%@", [NSThread currentThread]);
        });
        dispatch_async(queue, ^{
            NSLog(@"----------GCD4----%@", [NSThread currentThread]);
        });
    }
    

    异步并行队列执行后的打印信息如下:

    ThreadDemo[8552:11571678] ----------GCD1----<NSThread: 0x60000027e900>{number = 3, name = (null)}
    ThreadDemo[8552:11571679] ----------GCD4----<NSThread: 0x60000027e980>{number = 5, name = (null)}
    ThreadDemo[8552:11571680] ----------GCD3----<NSThread: 0x60000027e880>{number = 4, name = (null)}
    ThreadDemo[8552:11571681] ----------GCD2----<NSThread: 0x60000027e940>{number = 6, name = (null)}
    

    在异步并行队列中,线程的执行顺序不是固定的,并且创建了多个线程来同时执行。

    创建同步串行队列

    /**
     同步串行队列,不会开辟新的线程,在主线程中运行,执行方式是按照顺序依次执行
     */
    - (void)createSyncSerialThread {
        dispatch_queue_t queue = dispatch_queue_create("DISPATCH_QUEUE", DISPATCH_QUEUE_SERIAL);
        dispatch_sync(queue, ^{
            NSLog(@"----------GCD1----%@", [NSThread currentThread]);
        });
        dispatch_sync(queue, ^{
            NSLog(@"----------GCD2----%@", [NSThread currentThread]);
        });
        dispatch_sync(queue, ^{
            NSLog(@"----------GCD3----%@", [NSThread currentThread]);
        });
        dispatch_sync(queue, ^{
            NSLog(@"----------GCD4----%@", [NSThread currentThread]);
        });
    }
    

    同步串行队列执行后的打印信息如下:

    ThreadDemo[8729:11577620] ----------GCD1----<NSThread: 0x600000079800>{number = 1, name = main}
    ThreadDemo[8729:11577620] ----------GCD2----<NSThread: 0x600000079800>{number = 1, name = main}
    ThreadDemo[8729:11577620] ----------GCD3----<NSThread: 0x600000079800>{number = 1, name = main}
    ThreadDemo[8729:11577620] ----------GCD4----<NSThread: 0x600000079800>{number = 1, name = main}
    

    同步串行队列没有开辟新的线程去执行代码,而是在主线程中运行,并且是顺序执行
    同步并行队列的创建

    /**
     同步并行队列,不会开辟新的线程,在主线程中运行,执行方式是按照顺序依次执行
     */
    - (void)createSyncConcurrentThread {
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_sync(queue, ^{
            NSLog(@"----------GCD1----%@", [NSThread currentThread]);
        });
        dispatch_sync(queue, ^{
            NSLog(@"----------GCD2----%@", [NSThread currentThread]);
        });
        dispatch_sync(queue, ^{
            NSLog(@"----------GCD3----%@", [NSThread currentThread]);
        });
        dispatch_sync(queue, ^{
            NSLog(@"----------GCD4----%@", [NSThread currentThread]);
        });
        dispatch_sync(queue, ^{
            NSLog(@"----------GCD5----%@", [NSThread currentThread]);
        });
        dispatch_sync(queue, ^{
            NSLog(@"----------GCD6----%@", [NSThread currentThread]);
        });
    }
    

    同步并行队列执行后的打印信息如下:

    ThreadDemo[8842:11581676] ----------GCD1----<NSThread: 0x600000262a40>{number = 1, name = main}
    ThreadDemo[8842:11581676] ----------GCD2----<NSThread: 0x600000262a40>{number = 1, name = main}
    ThreadDemo[8842:11581676] ----------GCD3----<NSThread: 0x600000262a40>{number = 1, name = main}
    ThreadDemo[8842:11581676] ----------GCD4----<NSThread: 0x600000262a40>{number = 1, name = main}
    ThreadDemo[8842:11581676] ----------GCD5----<NSThread: 0x600000262a40>{number = 1, name = main}
    ThreadDemo[8842:11581676] ----------GCD6----<NSThread: 0x600000262a40>{number = 1, name = main}
    

    发现跟同步串行队列的执行情况一样,都是在主线程中运行,没有开辟新线程,并且是顺序执行的。

    另外还有一种队列是千万不能使用的:同步主队列,一旦使用就会面临整个程序卡死的状态:

    /**
     同步主队列,项目中千万不能用,会直接卡死
     */
    - (void)createSyncMainQueue {
        //获取主队列线程
        dispatch_queue_t queue = dispatch_get_main_queue();
        //下面添加的任务都会放到主队列中去执行
        dispatch_sync(queue, ^{
            NSLog(@"----------GCD1----%@", [NSThread currentThread]);
        });
        dispatch_sync(queue, ^{
            NSLog(@"----------GCD2----%@", [NSThread currentThread]);
        });
        dispatch_sync(queue, ^{
            NSLog(@"----------GCD3----%@", [NSThread currentThread]);
        });
        dispatch_sync(queue, ^{
            NSLog(@"----------GCD4----%@", [NSThread currentThread]);
        });
        dispatch_sync(queue, ^{
            NSLog(@"----------GCD5----%@", [NSThread currentThread]);
        });
        dispatch_sync(queue, ^{
            NSLog(@"----------GCD6----%@", [NSThread currentThread]);
        });
    }
    

    GCD的使用

    1、使用GCD异步加载图片然后在回去主线程刷新UI界面

    /**
     GCD简单实用1、异步加载图标,然后在主线程中刷新UI
     */
    - (void)downImageAndRefreshUI {
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_async(queue, ^{
            NSURL *url = [NSURL URLWithString:@"https://xxxxx.png"];
            NSData *data = [NSData dataWithContentsOfURL:url];
            UIImage *img = [UIImage imageWithData:data];
            dispatch_async(dispatch_get_main_queue(), ^{
                UIImageView *imageView = [[UIImageView alloc] initWithImage:img];
            });
        });
    }
    

    2、使用GCD创建定时器

    - (void)createTimerWithGCD {
        //这种方式创建的定时器只能执行一次
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            NSLog(@"11111");
        });
        
        //来看看另外一种定时器的实现方式
        dispatch_queue_t queue = dispatch_queue_create("timer", NULL);
        dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
        
        int64_t interval = (int64_t)(1 * NSEC_PER_SEC);//每秒执行一次
     //DISPATCH_TIME_NOW,dispatch_walltime(NULL, 0)
        dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, interval, 0);
        
        dispatch_source_set_event_handler(timer, ^{
            NSLog(@"xxxxxx");
    //        dispatch_source_cancel(self.timer);
     //       dispatch_suspend(timer);
        });
        dispatch_resume(timer);
    }
    **注意事项**,如果在实现的文职没有出现dispatch_source_cancel、dispatch_suspend,你会很神奇的发现,定时器不起作用,所以一定要实现这两个方法中的一个
    

    3、使用GCD延迟执行代码

    /**
     GCD延迟执行程序
     */
    - (void)delayGCD {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            NSLog(@"122");
        });
    }
    

    4、使用GCD来创建单例

    static GCDDemo *demo;
    + (instancetype)gcdDemo {
        if (nil == demo) {
            static dispatch_once_t onceToken;
            dispatch_once(&onceToken, ^{
                demo = [[GCDDemo alloc] init];
            });
        }
        return demo;
    }
    

    如果对象遵守了<NSCopying, NSMutableCopying>协议,需要在实现这两个方法的协议:

    - (id)copyWithZone:(NSZone *)zone ;
    - (id)mutableCopyWithZone:(NSZone *)zone;
    

    5、使用GCD的dispatch_semaphore_signal来FIFO进行网络请求

    首先了解下几个概念:

    dispatch_semaphore_create:创建一个信号量(semaphore)
    dispatch_semaphore_signal:信号通知,即让信号量+1
    dispatch_semaphore_wait:等待,直到信号量大于0时,即可操作,同时将信号量-1
    

    在开发的过程中曾经遇到这样一个问题,就是有多个航班,每个航班下面都会挂载有同行人信息,这个时候需求需要按照顺序去加载航班下面的同行人信息,解决的方法可以有多种,但是笔者在此使用的是dispatch_semaphore_signal来解决。
    首先把航班信息全部遍历一边,创建出每个查询同行人的对象保存在一个数组里面,然后调用dispatch_async的异步线程去加载数据,当数据加载完成的时候,把数组中的一个query去除,然后调用dispatch_semaphore_signal(weakSelf.semaphore);使得信号量加一进行下一次的请求,加载失败的时候不会对数组进行query的删除操作,会进行信号量加一进行下一次的请求,具体实现如下:

    -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
        
        
        SegmentInfoView *sectionView = [[SegmentInfoView alloc] init];
        
        FlightSegment *segment = [self.viewModel.segmentArray cs_objectWithIndex:section];
        [sectionView configViewWithSegment:segment];
        weakState(weakSelf, self)
        NSLog(@"...................................%d",section);
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:section];
    
       [self.viewModel doQueryPassengers:segment indexPath:indexPath response:^() {
    
                    [weakSelf loadBoardingPassData];
    
                    [weakSelf.tableView reloadData];
                }];
        return sectionView;
    }
    
    - (void)doQueryPassengers:(CSCheckInFlightSegment *)segment indexPath:(NSIndexPath *)indexPath response:(void(^)())response{
        if ([self.flightNumArray containsObject:segment]) {
            return;
        }
        [self.flightNumArray cs_addObj:segment];
    
        weakState(weakSelf, self)
        dispatch_async(self.dispatch_queue, ^{
            dispatch_semaphore_wait(weakSelf.semaphore, DISPATCH_TIME_FOREVER);
            //进行同行人网络接口查询
            PassengerQuery *passengerQuery = [[PassengerQuery alloc] init];
            [weakSelf.passengerQuerys cs_addObj:passengerQuery];
            dispatch_sync(dispatch_get_main_queue(), ^{
                [passengerQuery queryWithparameters:[weakSelf getQueryPassnegesParams:segment] queryWithSuccessBlock:^(id obj) {//请求成功
                    //删除loading状态
                    NSDictionary<NSNumber*,NSMutableArray*>* dict = nil;
                    for (NSDictionary<NSNumber*,NSMutableArray*>*cellDict in self.cellDataArray) {
                        NSNumber *nu = cellDict.allKeys.firstObject;
                        if (nu.integerValue == indexPath.section) {
                            dict = cellDict;
                            break;
                        }
                    }
                    if (dict != nil) {
                        [self.cellDataArray removeObject:dict];
                    }
                    for (Passenger *psg in obj) {
                        if ([@"NNY" isEqualToString:[segment.departCode uppercaseString]]) {
                            psg.hasNNY = true;
                        }
                    }
                    segment.passengers = obj;
                    [weakSelf configSegment:segment index:indexPath.section isQueryPsgs:true];
                    response();
                    NSLog(@"run task ............%d",indexPath.section);
                    NSLog(@"complete task .......%d",indexPath.section);
                    
                    dispatch_semaphore_signal(weakSelf.semaphore);
                    
                } failBlock:^(NSError *error) {//请求失败
                    if ([self.cellDataArray cs_objectWithIndex:indexPath.section] != nil) {
                        [self.cellDataArray removeObjectAtIndex:indexPath.section];
                    }
                    NSMutableArray *rowDataArray = [NSMutableArray array];
                    [rowDataArray cs_addObj:@{kPassengerLoadingFailCell:@""}];
                    [weakSelf.cellDataArray insertObject:@{@(indexPath.section):rowDataArray} atIndex:indexPath.section];
                    response();
                    NSLog(@"run task ............%d",indexPath.section);
                    NSLog(@"complete task .......%d",indexPath.section);
                    
                    dispatch_semaphore_signal(weakSelf.semaphore);
                }];
            });
            weakSelf.dispatch_cnt ++;
        });
    }
    

    如果没看明白我们就换另外一种实现方式

    /**
     信号量的使用
     */
    - (void)createGCDWithSignal {
        dispatch_semaphore_t sema = dispatch_semaphore_create(2);//2代表并发个数为2
        for (NSInteger index = 0; index < 50; index++) {
            dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                //在此处实现需要的代码逻辑
                dispatch_semaphore_signal(sema);//让信号量增加,执行下一次的操作
            });
        }
    }
    

    6、GCD中dispatch_group

    group就相当于是组的意思,可以在项目中创建多个线程组,然后在每个线程组中加入不同的任务,具体的实现方式:

    - (void)createGCDWithDispatch_group {
        dispatch_group_t group = dispatch_group_create();
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_group_async(group, queue, ^{
            NSLog(@"----------group1----%@", [NSThread currentThread]);
        });
        dispatch_group_async(group, queue, ^{
            NSLog(@"----------group2----%@", [NSThread currentThread]);
        });
        dispatch_group_async(group, queue, ^{
            NSLog(@"----------group3----%@", [NSThread currentThread]);
        });
        dispatch_group_async(group, queue, ^{
            NSLog(@"----------group4----%@", [NSThread currentThread]);
        });
        
    }
    

    加入group组中的任务相当于是并行执行,执行顺序不确定,从打印日志可以看出

    ThreadDemo[13231:11689884] ----------group2----<NSThread: 0x60400027d900>{number = 3, name = (null)}
    ThreadDemo[13231:11689887] ----------group4----<NSThread: 0x60400027dbc0>{number = 6, name = (null)}
    ThreadDemo[13231:11689883] ----------group3----<NSThread: 0x600000267ec0>{number = 5, name = (null)}
    ThreadDemo[13231:11689885] ----------group1----<NSThread: 0x60400027d8c0>{number = 4, name = (null)}
    

    此外在group组中加入dispatch_group_notify,相当于通知的作用,就是说当组中的全部任务执行完成之后,才开始执行dispatch_group_notify中的任务:

    dispatch_group_notify(group, queue, ^{
            NSLog(@"----------group_notify----%@", [NSThread currentThread]);
        });
    

    最后附上以上代码链接

    上述所有代码均可以在GCDDemo中查看,有需要可以自行获取

    相关文章

      网友评论

          本文标题:iOS中GCD的使用

          本文链接:https://www.haomeiwen.com/subject/wjfnpftx.html