美文网首页
iOS并发执行

iOS并发执行

作者: MeteorCode | 来源:发表于2017-10-09 18:08 被阅读7次

    平时运用总会遇到几个网络请求需要同时进行:

        dispatch_semaphore_t semaphore = dispatch_semaphore_create(0); //创建信号量
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); //创建全局并行
        dispatch_group_t group = dispatch_group_create();
        
        dispatch_group_async(group, queue, ^{
            
            NSLog(@"-->> 这是并发任务A");
            for (int i = 0; i<100; i++) {
                NSLog(@"正在处理A %d",i);
            }
            dispatch_semaphore_signal(semaphore);
        });
        
        dispatch_group_async(group, queue, ^{
            
            NSLog(@"-->> 这是并发任务B");
            for (int i = 0; i<100; i++) {
                NSLog(@"正在处理B %d",i);
            }
            dispatch_semaphore_signal(semaphore);
        });
        
        dispatch_group_async(group, queue, ^{
            NSLog(@"-->> 这是并发任务C");
            for (int i = 0; i<100; i++) {
                NSLog(@"正在处理C %d",i);
            }
            dispatch_semaphore_signal(semaphore);
        });
        
        dispatch_group_async(group, queue, ^{
            NSLog(@"-->> 这是并发任务D");
            for (int i = 0; i<100; i++) {
                NSLog(@"正在处理D %d",i);
            }
            dispatch_semaphore_signal(semaphore);
        });
        
        dispatch_group_notify(group, queue, ^{ //四个请求对应四次信号等待
            
            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);
            NSLog(@"----->>>> 渲染UI");
        });
    

    相关文章

      网友评论

          本文标题:iOS并发执行

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