美文网首页iOS多线程
iOS_多线程_GCD_顺序执行

iOS_多线程_GCD_顺序执行

作者: SwordDevil | 来源:发表于2022-09-29 14:20 被阅读0次

    多个任务同时执行,全部执行完毕再执行其他的操作

    (1)dispatch_group_async、dispatch_group_notify结合使用
    /// 队列组
    dispatch_group_t group = dispatch_group_create();
    /// 并发队列
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    
    dispatch_group_async(group, queue, ^{
        NSLog(@"任务一:%@",[NSThread currentThread]);
    });
    
    dispatch_group_async(group, queue, ^{
        NSLog(@"任务二:%@",[NSThread currentThread]);
    });
    
    dispatch_group_async(group, queue, ^{
        NSLog(@"任务三:%@",[NSThread currentThread]);
    });
    
    dispatch_group_notify(group, queue, ^{
        NSLog(@"所有任务执行完毕:%@",[NSThread currentThread]);
    });
    
    #打印结果:
    任务一、任务二、任务三(顺序不一定,因为都是异步同时执行的)都执行完成,才执行:所有任务执行完毕
    
    (2) 使用栅栏函数
    /// 自定义并发队列
    dispatch_queue_t queue = dispatch_queue_create("my_queue", DISPATCH_QUEUE_CONCURRENT);
    
    dispatch_async(queue, ^{
        NSLog(@"任务一:%@",[NSThread currentThread]);
    });
    
    dispatch_async(queue, ^{
        NSLog(@"任务二:%@",[NSThread currentThread]);
    });
    
    dispatch_async(queue, ^{
        NSLog(@"任务三:%@",[NSThread currentThread]);
    });
    
    dispatch_barrier_async(queue, ^{
        NSLog(@"所有任务执行完毕:%@",[NSThread currentThread]);
    });
    
    # 打印结果:
    2020-10-13 16:24:17.926220+0800 ThreadingDemo[26902:6624494] 任务二:{number = 4, name = (null)}
    2020-10-13 16:24:17.926227+0800 ThreadingDemo[26902:6624499] 任务一:{number = 6, name = (null)}
    2020-10-13 16:24:17.926220+0800 ThreadingDemo[26902:6624495] 任务三:{number = 5, name = (null)}
    2020-10-13 16:24:17.926396+0800 ThreadingDemo[26902:6624495] 所有任务执行完毕:{number = 5, name = (null)}
    

    以上的两种写法对于任务是同步的,是没有问题的。
    但是如果对于异步执行的任务,则会达不到顺序执行的,比如网络请求.
    因为异步,请求还没回来,dispatch_group_notify或dispatch_barrier_async已经执行了
    如果任务是异步的,可以使用信号量或者dispatch_group_enter、dispatch_group_leave事项

    # 比如下方任务是异步的网络请求,那么栅栏函数也是控制不住执行顺序的
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        
        dispatch_queue_t queue = dispatch_queue_create("my_queue", DISPATCH_QUEUE_CONCURRENT);
        dispatch_async(queue, ^{
            [self requestNetworkWithCallback:^{
                NSLog(@"任务1");
            }];
        });
        
        dispatch_async(queue, ^{
            [self requestNetworkWithCallback:^{
                NSLog(@"任务2");
            }];
        });
        
        dispatch_async(queue, ^{
            [self requestNetworkWithCallback:^{
                NSLog(@"任务3");
            }];
        });
        
        dispatch_barrier_async(queue, ^{
            NSLog(@"任务全部执行完成");
        });
        
    }
    
    /// 异步任务:模拟网络请求
    - (void)requestNetworkWithCallback:(void(^)(void))callback {
        dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
        dispatch_async(queue, ^{
            [NSThread sleepForTimeInterval:2];
            if (callback) {
                callback();
            }
        });
    }
    
    # 打印结果:(“任务全部执行完成”肯定都是先执行的)
    2020-10-14 09:36:32.053314+0800 ThreadingDemo[45423:6822309] 任务全部执行完成
    2020-10-14 09:36:34.053708+0800 ThreadingDemo[45423:6822308] 任务1
    2020-10-14 09:36:34.053729+0800 ThreadingDemo[45423:6822310] 任务2
    2020-10-14 09:36:34.053733+0800 ThreadingDemo[45423:6822307] 任务3
    
    (3)信号量

    信号量的作用:线程同步、线程加锁
    dispatch_semaphore_t dispatch_semaphore_create(long value):方法接收一个long类型的参数,返回一个dispatch_semaphore_t类型的信号量,值为传入的参数
    long dispatch_semaphore_wait(dispatch_semaphore_t dsema, dispatch_time_t timeout):接收一个信号和时间值,若信号的量为0,则会阻塞当前线程,知道信号量大于0或者经过输入的时间值;若信号量大于0,则会使信号量减1并返回,程序继续往下执行
    long dispatch_semaphore_signal(dispatch_semaphore_t dsema):使信号量加1并返回

    # 对于多个任务同时进行,执行完成后再执行其他任务,用单个信号量完成不了
    # 只能是一个个任务执行完成再执行另外一个任务
    # 使用场景:多张图片,一张张上传
    - (void)viewDidLoad {
        [super viewDidLoad];
        
        dispatch_queue_t queue = dispatch_queue_create("my_queue", DISPATCH_QUEUE_CONCURRENT);
        dispatch_async(queue, ^{
            /// 创建信号量,并设置为0
            dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
            
            [self requestNetworkWithTime:1 callback:^{
                NSLog(@"任务1");
                /// 信号量 + 1
                dispatch_semaphore_signal(semaphore);
            }];
            
            /// 判断如果信号量为0,则阻塞等待
            /// 信号量大于1,则会使信号量减 1,程序继续往下执行
            dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
            NSLog(@"任务2");
            
        });
        
    }
    
    /// 异步任务:模拟网络请求
    - (void)requestNetworkWithTime:(NSInteger )time callback:(void(^)(void))callback {
        dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
        dispatch_async(queue, ^{
            [NSThread sleepForTimeInterval:time];
            if (callback) {
                callback();
            }
        });
    }
    
    # 打印结果:
    2020-10-14 13:51:20.956845+0800 ThreadingDemo[59313:7012870] 任务1
    2020-10-14 13:51:20.957029+0800 ThreadingDemo[59313:7012871] 任务2
    
    # 创建多个信号,异步同时执行任务,都执行完成再执行其他操作
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        
        dispatch_group_t group = dispatch_group_create();
        dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
        
        dispatch_group_async(group, queue, ^{
            /// 创建信号1
            dispatch_semaphore_t semap = dispatch_semaphore_create(0);
            [self requestNetworkWithTime:2 callback:^{
                NSLog(@"任务1");
                dispatch_semaphore_signal(semap);
            }];
            dispatch_semaphore_wait(semap, DISPATCH_TIME_FOREVER);
        });
        
        dispatch_group_async(group, queue, ^{
            /// 创建信号2
            dispatch_semaphore_t semap = dispatch_semaphore_create(0);
            [self requestNetworkWithTime:1 callback:^{
                NSLog(@"任务2");
                dispatch_semaphore_signal(semap);
            }];
            dispatch_semaphore_wait(semap, DISPATCH_TIME_FOREVER);
        });
        
        dispatch_group_notify(group, queue, ^{
            NSLog(@"全部执行完成");
        });
    }
    
    /// 异步任务:模拟网络请求
    - (void)requestNetworkWithTime:(NSInteger )time callback:(void(^)(void))callback {
        dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
        dispatch_async(queue, ^{
            [NSThread sleepForTimeInterval:time];
            if (callback) {
                callback();
            }
        });
    }
    
    # 打印结果:
    2020-10-14 15:42:34.781421+0800 ThreadingDemo[76163:7169489] 任务2
    2020-10-14 15:42:35.781343+0800 ThreadingDemo[76163:7169490] 任务1
    2020-10-14 15:42:35.781643+0800 ThreadingDemo[76163:7169495] 全部执行完成
    
    (4)dispatch_group_enter/leave

    dispatch_group_enter 和 dispatch_group_leave 必须成对出现,否则会造成“死锁”
    dispatch_group_wait:如果enter数不等于leave数,则线程阻塞等待,若enter数与leave数相等则继续往下执行
    dispatch_group_notify:只有enter数和leave数相等,才会执行

    - (void)viewDidLoad {
        [super viewDidLoad];
        
        dispatch_group_t group = dispatch_group_create();
        
        dispatch_group_enter(group);
        [self requestNetworkWithTime:1 callback:^{
            NSLog(@"任务1");
            dispatch_group_leave(group);
        }];
        
        dispatch_group_enter(group);
        [self requestNetworkWithTime:2 callback:^{
            NSLog(@"任务2");
            dispatch_group_leave(group);
        }];
        
        /// 等待任务1、任务2执行完毕
        dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
        
        dispatch_group_enter(group);
        [self requestNetworkWithTime:2 callback:^{
            NSLog(@"任务3");
            dispatch_group_leave(group);
        }];
        
        dispatch_group_notify(group, dispatch_get_global_queue(0, 0), ^{
            NSLog(@"全部执行完成");
        });
    }
    
    /// 异步任务:模拟网络请求
    - (void)requestNetworkWithTime:(NSInteger )time callback:(void(^)(void))callback {
        dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
        dispatch_async(queue, ^{
            [NSThread sleepForTimeInterval:time];
            if (callback) {
                callback();
            }
        });
    }
    
    # 打印结果:
    2020-10-14 15:18:03.405899+0800 ThreadingDemo[74573:7126913] 任务1
    2020-10-14 15:18:04.407338+0800 ThreadingDemo[74573:7126917] 任务2
    2020-10-14 15:18:06.410904+0800 ThreadingDemo[74573:7126917] 任务3
    2020-10-14 15:18:06.411069+0800 ThreadingDemo[74573:7126917] 全部执行完成
    
    补充:栅栏函数dispatch_barrier使用教程

    dispatch_barrier_async:无需等待栅栏函数执行完成,会继续往下走(任务执行顺序:栅栏前的任务===》栅栏函数 ====》 栅栏函数后的任务)
    dispatch_barrier_sync:需要等待栅栏函数执行完才会执行栅栏后面的任务
    注意:
    (1)栅栏必须在并发队列执行 ,并且不能使用全局队列,否则栅栏函数就不起作用;
    dispatch_barrier_async 等同于 dispatch_async , dispatch_barrier_sync 等同于 dispatch_sync
    (2)理解的时候,必须要区分哪些是任务,哪些是普通代码

    # dispatch_barrier_async
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        
        NSLog(@"start");
        dispatch_queue_t queue = dispatch_queue_create("my_queue", DISPATCH_QUEUE_CONCURRENT);
        dispatch_async(queue, ^{
            NSLog(@"任务1");
        });
       
        dispatch_async(queue, ^{
            NSLog(@"任务2");
        });
        
        ///  因为是栅栏异步,所以栅栏函数和栅栏函数后面的任务都
        dispatch_barrier_async(queue, ^{
            NSLog(@"===== barrier ====");
        });
        NSLog(@"mid");
        dispatch_async(queue, ^{
            NSLog(@"任务3");
        });
        dispatch_async(queue, ^{
            NSLog(@"任务4");  
        });
        NSLog(@"last");
    }
    
    打印结果:
    2020-10-13 16:02:03.843934+0800 ThreadingDemo[26494:6576066] start
    2020-10-13 16:02:03.844143+0800 ThreadingDemo[26494:6576066] mid
    2020-10-13 16:02:03.844189+0800 ThreadingDemo[26494:6576341] 任务1
    2020-10-13 16:02:03.844182+0800 ThreadingDemo[26494:6576343] 任务2
    2020-10-13 16:02:03.844231+0800 ThreadingDemo[26494:6576066] last
    2020-10-13 16:02:03.844300+0800 ThreadingDemo[26494:6576343] ===== barrier ====
    2020-10-13 16:02:03.844375+0800 ThreadingDemo[26494:6576343] 任务3
    2020-10-13 16:02:03.844381+0800 ThreadingDemo[26494:6576341] 任务4
    
    # dispatch_barrier_sync
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        
        NSLog(@"start");
        dispatch_queue_t queue = dispatch_queue_create("my_queue", DISPATCH_QUEUE_CONCURRENT);
        dispatch_async(queue, ^{
            NSLog(@"任务1");
        });
        
        dispatch_async(queue, ^{
            NSLog(@"任务2");
        });
        
        /// 因为是同步栅栏,执行顺序:栅栏前 ===》栅栏函数 ====》 栅栏后
        dispatch_barrier_sync(queue, ^{
            NSLog(@"===== barrier ====");
        });
        NSLog(@"mid");
        dispatch_async(queue, ^{
            NSLog(@"任务3");
        });
        dispatch_async(queue, ^{
            NSLog(@"任务4");
        });
        NSLog(@"last");
    }
    
    打印结果:
    2020-10-13 16:02:42.629822+0800 ThreadingDemo[26527:6577198] start
    2020-10-13 16:02:42.630035+0800 ThreadingDemo[26527:6577356] 任务1
    2020-10-13 16:02:42.630037+0800 ThreadingDemo[26527:6577360] 任务2
    2020-10-13 16:02:42.630155+0800 ThreadingDemo[26527:6577198] ===== barrier ====
    2020-10-13 16:02:42.630224+0800 ThreadingDemo[26527:6577198] mid
    2020-10-13 16:02:42.630310+0800 ThreadingDemo[26527:6577198] last
    2020-10-13 16:02:42.630327+0800 ThreadingDemo[26527:6577360] 任务3
    2020-10-13 16:02:42.630374+0800 ThreadingDemo[26527:6577356] 任务4
    

    相关文章

      网友评论

        本文标题:iOS_多线程_GCD_顺序执行

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