美文网首页
iOS 使用信号量控制网络请求顺序

iOS 使用信号量控制网络请求顺序

作者: henu_Larva | 来源:发表于2017-12-26 10:59 被阅读165次
        dispatch_semaphore_t sem = dispatch_semaphore_create(1);
        dispatch_queue_t queue = dispatch_queue_create("lalala", NULL);
        
        dispatch_async(queue, ^{
            dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
            //network request 1
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                NSLog(@"request1 done");
                dispatch_semaphore_signal(sem);
            });
        });
        
        dispatch_async(queue, ^{
            dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
            //network request 2
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                NSLog(@"request2 done");
                dispatch_semaphore_signal(sem);
            });
        });
        
        dispatch_async(queue, ^{
            dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
            //network request 3
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                NSLog(@"request3 done");
                dispatch_semaphore_signal(sem);
            });
        });
    

    其中 dispatch_semaphore_create(1)括号内的值是同时执行的事件个数。
    以上。

    相关文章

      网友评论

          本文标题:iOS 使用信号量控制网络请求顺序

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