iOS - 网络请求并发和同步

有时我们需要将多个网络请求并行或者串行执行完后回到主线程执行某些操作,这时候我们可以借助dispatch_semaphore来实现这个功能,下面模拟三个网络请求,实际中NSUrlSession中的方法本身就是异步的,所以不用开辟异步线程。

    __block NSString *string1;
    __block NSString *string2;
    __block NSString *string3;
    
//    串行
//    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        [NSThread sleepForTimeInterval:8];
//        string1 = @"任务1";
//        NSLog(@"任务1-start");
//        dispatch_semaphore_signal(semaphore);
//    });
//    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        [NSThread sleepForTimeInterval:5];
//        string2 = @"任务2";
//        NSLog(@"任务2-start");
//        dispatch_semaphore_signal(semaphore);
//    });
//    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        [NSThread sleepForTimeInterval:5];
//        string3 = @"任务3";
//        NSLog(@"任务3-start");
//        dispatch_semaphore_signal(semaphore);
//    });
//    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
//    NSLog(@"%@-%@-%@",string1,string2,string3);
    
//    并行
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [NSThread sleepForTimeInterval:8];
        string1 = @"任务1";
        NSLog(@"任务1-start");
        dispatch_semaphore_signal(semaphore);
    });
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [NSThread sleepForTimeInterval:5];
        string2 = @"任务2";
        NSLog(@"任务2-start");
        dispatch_semaphore_signal(semaphore);
    });
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [NSThread sleepForTimeInterval:5];
        string3 = @"任务3";
        NSLog(@"任务3-start");
        dispatch_semaphore_signal(semaphore);
    });
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    NSLog(@"%@-%@-%@",string1,string2,string3);

你可能感兴趣的:(iOS - 网络请求并发和同步)