多线程等我爱编程

iOS开发之AFNetworking 3.0 如何实现在多个网络

2018-04-12  本文已影响260人  朱晓晓的技术博客

用信号量就可以解决:

dispatch_semaphore_t semaphore = dispatch_semaphore_create(1);
    dispatch_queue_t quene = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    //任务1
    dispatch_async(quene, ^{
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
           [self loadDetailData];  //请求A
        dispatch_semaphore_signal(semaphore);
    });
    //任务2
    dispatch_async(quene, ^{
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
            [self loadHotCommentData]; //请求B
        dispatch_semaphore_signal(semaphore);
    });
    //任务3
    dispatch_async(quene, ^{
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        [self loadHotCommentData]; //请求C
        dispatch_semaphore_signal(semaphore);
    });
    //任务4
    dispatch_async(quene, ^{
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        [self loadHotCommentData]; //请求D
        dispatch_semaphore_signal(semaphore);
    });
注意:Google一下 “ iOS convert async to sync ” 注意用信号量的方式,异步转同步后的方法只能在子线程调用,不然会阻塞主线程

参考链接:http://www.cocoachina.com/bbs/read.php?tid-1689119-page-2.html

上一篇下一篇

猜你喜欢

热点阅读