iOS多线程 - GCD中的栅栏函数

一、什么是栅栏函数

dispatch_barrier_async函数,在进程管理中起到一个栅栏的作用,它等待所有位于barrier函数之前的操作执行完毕后执行,并且在barrier函数执行之后,barrier函数之后的操作才会得到执行,该函数需要同dispatch_queue_create函数生成的DISPATCH_QUEUE_CONCURRENT队列一起使用。

二、dispatch_barrier_async函数的作用

  1. 实现高效率的数据库访问和文件访问
  2. 避免数据竞争

三、dispatch_barrier_async实例

dispatch_queue_t queue = dispatch_queue_create("testqueue", DISPATCH_QUEUE_CONCURRENT);
    
    dispatch_async(queue, ^{
        NSLog(@"----1-----%@", [NSThread currentThread]);
    });
    dispatch_async(queue, ^{
        NSLog(@"----2-----%@", [NSThread currentThread]);
    });
    
    dispatch_barrier_async(queue, ^{
        NSLog(@"----barrier-----%@", [NSThread currentThread]);
    });
    
    dispatch_async(queue, ^{
        NSLog(@"----3-----%@", [NSThread currentThread]);
    });
    dispatch_async(queue, ^{
        NSLog(@"----4-----%@", [NSThread currentThread]);
    });

输出结果

----2-----{number = 3, name = (null)}
----1-----{number = 4, name = (null)}
----barrier-----{number = 4, name = (null)}
----3-----{number = 4, name = (null)}
----4-----{number = 3, name = (null)}

四、dispatch_barrier_async和dispatch_barrier_sync的区别

1. dispatch_barrier_sync
dispatch_queue_t queue = dispatch_queue_create("testqueue", DISPATCH_QUEUE_CONCURRENT);
    NSLog(@"start");
    dispatch_async(queue, ^{
        NSLog(@"---test1---");
    });
    dispatch_async(queue, ^{
        NSLog(@"---test12---");
    });
    
    dispatch_barrier_sync(queue, ^{
        NSLog(@"----barrier-----");
    });
    
    NSLog(@"aaa");
    
    dispatch_async(queue, ^{
        NSLog(@"---test3---");
    });
    dispatch_async(queue, ^{
        NSLog(@"---test4---");
    });
    NSLog(@"last");

运行结果

start
---test1---
---test12---
----barrier-----
aaa
last
---test3---
---test4---

2. dispatch_barrier_sync
dispatch_queue_t queue = dispatch_queue_create("testqueue", DISPATCH_QUEUE_CONCURRENT);
    NSLog(@"start");
    dispatch_async(queue, ^{
        NSLog(@"---test1---");
    });
    dispatch_async(queue, ^{
        NSLog(@"---test12---");
    });
    
    dispatch_barrier_async(queue, ^{
        NSLog(@"----barrier-----");
    });
    
    NSLog(@"aaa");
    
    dispatch_async(queue, ^{
        NSLog(@"---test3---");
    });
    dispatch_async(queue, ^{
        NSLog(@"---test4---");
    });
    NSLog(@"last");

运行结果

start
aaa
last
---test1---
---test12---
----barrier-----
---test3---
---test4---

跟sync的情况相比,aaa、last的输出位置完全不同,async的时候aaa的输出在test1结束之前,sync的aaa输出在test1结束之后。

3. 总结

dispatch_barrier_sync(queue,void(^block)())会将queue中barrier前面添加的任务block全部执行后,再执行barrier任务的block,再执行barrier后面添加的任务block.

dispatch_barrier_async(queue,void(^block)())会将queue中barrier前面添加的任务block只添加不执行,继续添加barrier的block,再添加barrier后面的block,同时不影响主线程(或者操作添加任务的线程)中代码的执行!

你可能感兴趣的:(iOS多线程 - GCD中的栅栏函数)