iOS dispatch_group 和 dispatch_barrier注意事项

1.第一种情况:dispatch_group_async直接执行具体任务,内部没有开启别的线程

dispatch_queue_t queue = dispatch_get_global_queue(0, 0);

    dispatch_group_t group = dispatch_group_create();

    dispatch_group_async(group, queue, ^{

        for (int i=10; i>0; i--) {

            NSLog(@"%@ ++%d",[NSThread currentThread],i);

        }

    });

    dispatch_group_async(group, queue, ^{

        for (int i=10; i>0; i--) {

            NSLog(@"%@ ==%d",[NSThread currentThread],i);

        }

    });

    dispatch_group_notify(group, queue, ^{

        NSLog(@"group:over");

    });

会等所有任务执行完毕打印group:over

2021-05-13 17:04:34.606987+0800 test[20638:8113573] group:over

2.第二种情况:dispatch_group_async内嵌dispatch_async或者dispatch_sync操作,需要借助dispatch_group_enter和dispatch_group_enter,否则不会等到所有任务执行完毕就会打印group:over

dispatch_queue_t queue = dispatch_get_global_queue(0, 0);

    dispatch_group_t group = dispatch_group_create();

    dispatch_group_async(group, queue, ^{

        dispatch_group_enter(group);

        dispatch_sync(queue, ^{

            for(inti=10; i>0; i--) {

                NSLog(@"%@ ++%d",[NSThread currentThread],i);

            }

            dispatch_group_leave(group);

        });

    });

    dispatch_group_async(group, queue, ^{

        dispatch_group_enter(group);

        dispatch_sync(queue, ^{

            for(inti=10; i>0; i--) {

                NSLog(@"%@ ==%d",[NSThread currentThread],i);

            }

            dispatch_group_leave(group);

        });

    });

    dispatch_group_notify(group, queue, ^{

        NSLog(@"group:over");

    });


会等所有任务执行完毕打印group:over

2021-05-13 16:56:55.015755+0800 test[19249:8100876] group:over


3.dispatch_barrier_async和dispatch_barrier_sync不能使用系统的全局并发队列,否则不起作用

区别:

dispatch_barrier_sync在主线程执行,执行完当前任务才能走后面的代码

dispatch_barrier_async在子线程执行,立刻返回,无需的等待当前任务执行完毕即可走后面的代码

你可能感兴趣的:(iOS dispatch_group 和 dispatch_barrier注意事项)