天天看点

GCD栅栏

当任务需要异步进行,但是这些任务需要分成两组来执行,第一组完成之后才能进行第二组的操作。这时候就用了到GCD的栅栏方法dispatch_barrier_async。

- (IBAction)barrierGCD:(id)sender {

    // 并发队列

    dispatch_queue_t queue = dispatch_queue_create("test", DISPATCH_QUEUE_CONCURRENT);

    // 异步执行

    dispatch_async(queue, ^{

        for (int i = 0; i < 3; i++) {

            NSLog(@"栅栏:并发异步1   %@",[NSThread currentThread]);

        }

    });

    dispatch_async(queue, ^{

        for (int i = 0; i < 3; i++) {

            NSLog(@"栅栏:并发异步2   %@",[NSThread currentThread]);

        }

    });

    dispatch_barrier_async(queue, ^{

        NSLog(@"------------barrier------------%@", [NSThread currentThread]);

        NSLog(@"******* 并发异步执行,但是34一定在12后面 *********");

    });

    dispatch_async(queue, ^{

        for (int i = 0; i < 3; i++) {

            NSLog(@"栅栏:并发异步3   %@",[NSThread currentThread]);

        }

    });

    dispatch_async(queue, ^{

        for (int i = 0; i < 3; i++) {

            NSLog(@"栅栏:并发异步4   %@",[NSThread currentThread]);

        }

    });

}

上面代码的打印结果如下,开启了多条线程,所有任务都是并发异步进行。但是第一组完成之后,才会进行第二组的操作。

栅栏:并发异步1   <NSThread: 0x60000026d740>{number = 3, name = (null)}

栅栏:并发异步2   <NSThread: 0x60000026e480>{number = 6, name = (null)}

栅栏:并发异步1   <NSThread: 0x60000026d740>{number = 3, name = (null)}

栅栏:并发异步2   <NSThread: 0x60000026e480>{number = 6, name = (null)}

栅栏:并发异步1   <NSThread: 0x60000026d740>{number = 3, name = (null)}

栅栏:并发异步2   <NSThread: 0x60000026e480>{number = 6, name = (null)}

 ------------barrier------------<NSThread: 0x60000026e480>{number = 6, name = (null)}

******* 并发异步执行,但是34一定在12后面 *********

栅栏:并发异步4   <NSThread: 0x60000026d740>{number = 3, name = (null)}

栅栏:并发异步3   <NSThread: 0x60000026e480>{number = 6, name = (null)}

栅栏:并发异步4   <NSThread: 0x60000026d740>{number = 3, name = (null)}

栅栏:并发异步3   <NSThread: 0x60000026e480>{number = 6, name = (null)}

栅栏:并发异步4   <NSThread: 0x60000026d740>{number = 3, name = (null)}

栅栏:并发异步3   <NSThread: 0x60000026e480>{number = 6, name = (null)}

继续阅读