美文网首页
多个网络请求中GCD信号量的使用

多个网络请求中GCD信号量的使用

作者: 行走的风车 | 来源:发表于2017-05-08 18:39 被阅读64次
        //信号量
        dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
        //创建全局并行
        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, ^{
            [self getAdvertList:^{ //这个block是此网络任务异步请求结束时调用的,代表着网络请求的结束.
            //一个任务结束时标记一个信号量
                 dispatch_semaphore_signal(semaphore);
            }];
        });
        //任务二
        dispatch_group_async(group, queue, ^{
            [self getHotCultureList:^{
                dispatch_semaphore_signal(semaphore);
            }];
        });
        //任务三
        dispatch_group_async(group, queue, ^{
            [self getSurroundCulture:^{
                dispatch_semaphore_signal(semaphore);
            }];
        });
        //任务四
        dispatch_group_async(group, queue, ^{
            [self getMySubscibe:^{
                 dispatch_semaphore_signal(semaphore);
            }];
    
        });
        //任务五
        dispatch_group_async(group, queue, ^{
            [self getRecommendCulture:^{
                 dispatch_semaphore_signal(semaphore);
            }];
        });
        //任务六
        dispatch_group_async(group, queue, ^{
             [self getNews:^{
                  dispatch_semaphore_signal(semaphore);
             }];
        });
    
        dispatch_group_notify(group, queue, ^{
        //6个任务,6个信号等待.
            dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
            dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
            dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
            dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
            dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
            dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
            //这里就是所有异步任务请求结束后执行的代码
             [self.homeTableView.mj_header endRefreshing];
    
        });
    -(void)getAdvertList:(void(^)())finish{ 
        //网络请求..成功后调用一下finish,失败也调用finish
    }
    

    相关文章

      网友评论

          本文标题:多个网络请求中GCD信号量的使用

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