dispatch_barrier_async与dispatch_barrier_sync的区别

2,356 阅读1分钟

#dispatch_barrier_async

void dispatch_barrier_async(dispatch_queue_t queue, dispatch_block_t block);

block不会立即执行及栅栏之后添加到队列中的任务块不会立即执行,而是等到队列中进行中的任务完成后,再执行

dispatch_queue_t t = dispatch_queue_create("3", DISPATCH_QUEUE_CONCURRENT);for (int i = 0;  i < 100;  i++) {        dispatch_async(t, ^{            NSLog(@"方法开头%d----%@",i,[NSThread currentThread]);            dispatch_barrier_async(t, ^{                [mutary addObject:[NSNumber numberWithInt:i]];                NSLog(@"栅栏%d----%@",i,[NSThread currentThread]);            });
            dispatch_async(t, ^{                        NSLog(@"栅栏后%d----%@",i,[NSThread currentThread]);                    });            NSLog(@"方法结尾%d----%@",i,[NSThread currentThread]);        });    }

方法执行过程是:遍历开始为队列增添任务,同时增添的任务开始开辟线程执行;任务执行到栅栏时,将栅栏及栅栏后的任务添加到当前队列任务中,等到当前执行的任务结束后再执行栅栏及栅栏之后的任务。

注意:队列需要是自己通过dispatch_queue_create创建出来的。


#dispatch_barrier_sync

将栅栏块提交到队列同步执行,和dispatch_barrier_sync 不同,函数在栅栏块执行完成之前不会返回。如果对当前队列调用该函数会导致死锁。

当栅栏块到达私人并行队列前端时,不会立即执行。队列等到当前执行的任务块结束之后才执行。那时候,队列通过自己执行栅栏块。任何在栅栏快之后提交的块在栅栏快完成之前不会执行。