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

2017-12-26  本文已影响165人  henu_Larva
    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)括号内的值是同时执行的事件个数。
以上。

上一篇下一篇

猜你喜欢

热点阅读