您的位置:首页 > 移动开发 > IOS开发

dispatch_barrier_async 隐藏的坑

2015-12-11 15:10 405 查看
今天在看文档的时候无意中发现的一个坑

* When submitted to a a global queue or to a queue not created with the

 * DISPATCH_QUEUE_CONCURRENT attribute, barrier blocks behave identically to

 * blocks submitted with the dispatch_async()/dispatch_sync() API.

本来以为DISPATCH_QUEUE_CONCURRENT的queue都没有问题,但是看到最后发现global queue也不起作用。

关于global queue :

@function dispatch_get_global_queue

 *

 * @abstract

 * Returns a well-known global concurrent queue of a given quality of service

  * class.

开来barrier只支持使用dispatch_queue_create创建出来的并行queue了。

做个测试:

#define LOG(...) {NSLog(@"begin"); \

                   __VA_ARGS__ \

                 NSLog(@"end");}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    

    

    LOG(dispatch_queue_t queue =
dispatch_queue_create("connect queue",
DISPATCH_QUEUE_CONCURRENT);

        //dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

        dispatch_async(queue, ^{

        sleep(2.f);

        NSLog(@"one");

    });

        

        dispatch_barrier_async(queue, ^{

        NSLog(@"barrier");

    });

        dispatch_async(queue, ^{

        NSLog(@"two");

    });)

      

    return
YES;

}

LOG输出:

2015-12-11 14:56:14.538 iOSTips[1961:115128] begin

2015-12-11 14:56:14.539 iOSTips[1961:115128] end

2015-12-11 14:56:16.544 iOSTips[1961:115327] one

2015-12-11 14:56:16.545 iOSTips[1961:115327] barrier

2015-12-11 14:56:16.545 iOSTips[1961:115327] two

barrier在这个时候是起作用的。再来看看global queue

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    

    

    LOG(dispatch_queue_t queue =
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,
0);

        dispatch_async(queue, ^{

        sleep(2.f);

        NSLog(@"one");

    });

        

        dispatch_barrier_async(queue, ^{

        NSLog(@"barrier");

    });

        dispatch_async(queue, ^{

        NSLog(@"two");

    });)

    

    return
YES;

LOG输出:

2015-12-11 15:04:49.094 iOSTips[2068:122004] begin

2015-12-11 15:04:49.095 iOSTips[2068:122004] end

2015-12-11 15:04:49.095 iOSTips[2068:122120] barrier

2015-12-11 15:04:49.095 iOSTips[2068:122099] two

2015-12-11 15:04:51.095 iOSTips[2068:122210] one


仔细看LOG输出啊,以后别采坑啦~~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息