多個網路請求中GCD訊號量的使用

weixin_33711641發表於2017-05-08
    //訊號量
    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
}

相關文章