美文网首页
GCD同步任务作用

GCD同步任务作用

作者: 遥远不是北_ | 来源:发表于2017-02-27 23:13 被阅读61次

    GCD同步任务作用

    • 当多个任务之间有依赖关系时,可以将任务定义成同步的.

    • 需求 : 登陆->付费->下载->通知用户

    代码演练

    建立依赖关系

    //点击屏幕触发事件
    - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
        
        //调用
        [self GCDDemo];
    }
    
    - (void)GCDDemo {
        
        //全局队列
        dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
        
        //同步任务加载
        dispatch_sync(queue, ^{
        
           // 查看当前线程
            NSLog(@"登录-%@",[NSThread currentThread]);
        });
    
        dispatch_sync(queue, ^{
            NSLog(@"付费-%@",[NSThread currentThread]);
        });
        
        dispatch_sync(queue, ^{
            NSLog(@"下载-%@",[NSThread currentThread]);
        });
        
        //执行完耗时操作后回到主线程
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"通知用户-%@",[NSThread currentThread]);
        });
        
    }
    
    
    • 打印结果
    • 问题 : 依赖关系虽然有了,但是耗时的网络操作(登陆->付费->下载)都在主线程中执行的.需要优化.
    2017-02-23 20:56:19.702 同步任务作用[8315:462677] 登录-<NSThread: 0x608000068200>{number = 1, name = main}
    2017-02-23 20:56:19.702 同步任务作用[8315:462677] 付费-<NSThread: 0x608000068200>{number = 1, name = main}
    2017-02-23 20:56:19.703 同步任务作用[8315:462677] 下载-<NSThread: 0x608000068200>{number = 1, name = main}
    2017-02-23 20:56:19.703 同步任务作用[8315:462677] 通知用户-<NSThread: 0x608000068200>{number = 1, name = main}
    
    

    依赖关系优化

    • 使用异步任务在子线程中建立依赖关系
    - (void)GCDDemo {
        
        //全局队列
        dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
        
        //异步任务 开启子线程
        dispatch_async(queue, ^{
    
             //同步任务加载
            dispatch_sync(queue, ^{
        
            // 查看当前线程
            NSLog(@"登录-%@",[NSThread currentThread]);
        });
            
            dispatch_sync(queue, ^{
                NSLog(@"付费-%@",[NSThread currentThread]);
            });
            
            dispatch_sync(queue, ^{
                NSLog(@"下载-%@",[NSThread currentThread]);
            });
            
            //执行完耗时操作后回到主线程 
        dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"通知用户-%@",[NSThread currentThread]);
            });
        });
        
    }
    
    • 打印结果 没有问题
    • 耗时操作都在子线程中执行
    2017-02-23 21:01:48.256 同步任务作用[8423:467767] 登录-<NSThread: 0x600000075100>{number = 3, name = (null)}
    2017-02-23 21:01:48.256 同步任务作用[8423:467767] 付费-<NSThread: 0x600000075100>{number = 3, name = (null)}
    2017-02-23 21:01:48.256 同步任务作用[8423:467767] 下载-<NSThread: 0x600000075100>{number = 3, name = (null)}
    2017-02-23 21:01:48.257 同步任务作用[8423:467733] 通知用户-<NSThread: 0x60000006b180>{number = 1, name = main}
    

    总结:

    • 同步任务有堵塞线程的特点(一个任务一个任务的执行)

    • 同步任务会在当前线程执行

    • 如果想使用同步任务 让任务依次执行 但是还要在子线程执行 那么必须和异步任务配合使用

    相关文章

      网友评论

          本文标题:GCD同步任务作用

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