iOS 多线程-GCD 之dispatch_set_target

2020-02-21  本文已影响0人  TaoGeNet
dispatch_set_target_queue(dispatch_object_t object, dispatch_queue_t queue);

dispatch_set_target_queue 函数有两个作用:第一,变更队列的执行优先级;第二,目标队列可以成为原队列的执行阶层。

第一个参数是要执行变更的队列(不能指定主队列和全局队列)
第二个参数是目标队列

变更优先级

//优先级变更的串行队列,初始是默认优先级
dispatch_queue_t serialQueue = dispatch_queue_create("com.gcd.setTargetQueue.serialQueue", NULL);

//优先级不变的串行队列(参照),初始是默认优先级
dispatch_queue_t serialDefaultQueue = dispatch_queue_create("com.gcd.setTargetQueue.serialDefaultQueue", NULL);

//变更前
dispatch_async(serialQueue, ^{
    NSLog(@"1");
});
dispatch_async(serialDefaultQueue, ^{
    NSLog(@"2");
});

//获取优先级为后台优先级的全局队列
dispatch_queue_t globalDefaultQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);
//变更优先级
dispatch_set_target_queue(serialQueue, globalDefaultQueue);

//变更后
dispatch_async(serialQueue, ^{
    NSLog(@"1");
});
dispatch_async(serialDefaultQueue, ^{
    NSLog(@"2");
});

2017-02-28 21:06:03.474 GCDLearn[1108:53387] 1
2017-02-28 21:06:03.474 GCDLearn[1108:53396] 2
2017-02-28 21:06:03.474 GCDLearn[1108:53396] 2
2017-02-28 21:06:03.475 GCDLearn[1108:53401] 1

设置执行层

dispatch_queue_t serialQueue1 = dispatch_queue_create("com.gcd.setTargetQueue2.serialQueue1", NULL);
dispatch_queue_t serialQueue2 = dispatch_queue_create("com.gcd.setTargetQueue2.serialQueue2", NULL);
dispatch_queue_t serialQueue3 = dispatch_queue_create("com.gcd.setTargetQueue2.serialQueue3", NULL);
dispatch_queue_t serialQueue4 = dispatch_queue_create("com.gcd.setTargetQueue2.serialQueue4", NULL);
dispatch_queue_t serialQueue5 = dispatch_queue_create("com.gcd.setTargetQueue2.serialQueue5", NULL);

dispatch_async(serialQueue1, ^{
    NSLog(@"1");
});
dispatch_async(serialQueue2, ^{
    NSLog(@"2");
});
dispatch_async(serialQueue3, ^{
    NSLog(@"3");
});
dispatch_async(serialQueue4, ^{
    NSLog(@"4");
});
dispatch_async(serialQueue5, ^{
    NSLog(@"5");
});

//创建目标串行队列
dispatch_queue_t targetSerialQueue = dispatch_queue_create("com.gcd.setTargetQueue2.targetSerialQueue", NULL);

//设置执行阶层
dispatch_set_target_queue(serialQueue1, targetSerialQueue);
dispatch_set_target_queue(serialQueue2, targetSerialQueue);
dispatch_set_target_queue(serialQueue3, targetSerialQueue);
dispatch_set_target_queue(serialQueue4, targetSerialQueue);
dispatch_set_target_queue(serialQueue5, targetSerialQueue);

三、利用dispatch source 实现定时器功能

    //1.创建类型为 定时器类型的 Dispatch Source
    //1.1将定时器设置在主线程
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
    //1.2设置定时器每一秒执行一次
    dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), 1ull * NSEC_PER_SEC, 0);
    //1.3设置定时器执行的动作
    dispatch_source_set_event_handler(_timer, ^{
        //在这里实现业务逻辑...
        NSLog(@"!!!");
    });
    //2.启动定时器
    dispatch_resume(_timer);

参考:
多线程-GCD 之dispatch_set_target_queue
iOS 并发编程 Dispatch_source 最完整总结

上一篇下一篇

猜你喜欢

热点阅读