dispatch_barrier 大坑理解

dispatch_queue_t queue = dispatch_queue_create("com.test.threeTask", DISPATCH_QUEUE_CONCURRENT);

    dispatch_async(queue, ^{

        NSThread * thread = [NSThread currentThread];

        NSLog(@"%@=123",thread);

    });

    dispatch_async(queue, ^{

        NSThread * thread = [NSThread currentThread];

        NSLog(@"%@=456",thread);

    });

    dispatch_barrier_async(queue, ^{

        NSThread * thread = [NSThread currentThread];

        NSLog(@"%@=789",thread);

    });

    dispatch_async(queue, ^{

        NSThread * thread = [NSThread currentThread];

        NSLog(@"%@=10",thread);

    });

输出结构 123 或 456, 一定 789, 然后 10.

当这个barrier作用范围是在当前线程中,并不是只和queue有关系,同一个queue在不同的线程中,就不起作用了。

例如:

dispatch_async(queue, ^{

        NSThread * thread = [NSThread currentThread];

        NSLog(@"%@=outside==123",thread);

        dispatch_async(queue, ^{

            NSThread * thread = [NSThread currentThread];

            NSLog(@"%@=123",thread);

        });

    });

    dispatch_async(queue, ^{

        NSThread * thread = [NSThread currentThread];

        NSLog(@"%@=456",thread);

    });

    dispatch_barrier_async(queue, ^{

        NSThread * thread = [NSThread currentThread];

        NSLog(@"%@=789",thread);

    });

    dispatch_async(queue, ^{

        NSThread * thread = [NSThread currentThread];

        NSLog(@"%@=10",thread);

    });

这个时候123就不一定在 789前面了。但 “outside==123”一定在789前面。


当这个barrier作用的队列必须是自己创建的队列,不能用global队列,这个亲自测试过了,用globbal队列就不起作用了。

你可能感兴趣的:(dispatch_barrier 大坑理解)