『ios』GCD补习 dispatch_set_target_q
2018-10-22 本文已影响27人
butterflyer
image.png
今天看到YYKit源码的时候,看到这个GCD函数,dispatch_set_target_queue
经过查询资料加自己测试验证,算是了解一些,下面分享下结果。
//第一个参数是要执行变更的队列(不能指定主队列和全局队列)
//第二个参数是目标队列(指定全局队列)
dispatch_set_target_queue(dispatch_object_t object,
dispatch_queue_t _Nullable queue);
dispatch_queue_t targetQueue = dispatch_queue_create("targetQueue", DISPATCH_QUEUE_SERIAL);//目标队列
dispatch_queue_t queue1 = dispatch_queue_create("queue1", DISPATCH_QUEUE_SERIAL);//串行队列
dispatch_queue_t queue2 = dispatch_queue_create("queue1", DISPATCH_QUEUE_CONCURRENT);//并发队列
dispatch_async(queue2, ^{
NSLog(@"job3 in");
[NSThread sleepForTimeInterval:2.f];
NSLog(@"job3 out");
});
dispatch_async(queue2, ^{
NSLog(@"job2 in");
[NSThread sleepForTimeInterval:1.f];
NSLog(@"job2 out");
});
dispatch_async(queue1, ^{
NSLog(@"job1 in");
[NSThread sleepForTimeInterval:3.f];
NSLog(@"job1 out");
});
下面是打印结果,可以看出是异步并行的。
2018-10-22 11:18:35.300821+0800 threadTest[82021:2951083] job2 in
2018-10-22 11:18:35.300820+0800 threadTest[82021:2951081] job1 in
2018-10-22 11:18:35.300820+0800 threadTest[82021:2951082] job3 in
2018-10-22 11:18:36.304771+0800 threadTest[82021:2951083] job2 out
2018-10-22 11:18:37.301503+0800 threadTest[82021:2951082] job3 out
2018-10-22 11:18:38.304793+0800 threadTest[82021:2951081] job1 out
下面是加上dispatch_set_target_queue的测试
dispatch_queue_t targetQueue = dispatch_queue_create("targetQueue", DISPATCH_QUEUE_SERIAL);//目标队列
dispatch_queue_t queue1 = dispatch_queue_create("queue1", DISPATCH_QUEUE_SERIAL);//串行队列
dispatch_queue_t queue2 = dispatch_queue_create("queue1", DISPATCH_QUEUE_CONCURRENT);//并发队列
//设置参考
dispatch_set_target_queue(queue1, targetQueue);
dispatch_set_target_queue(queue2, targetQueue);
dispatch_async(queue2, ^{
NSLog(@"job3 in");
[NSThread sleepForTimeInterval:2.f];
NSLog(@"job3 out");
});
dispatch_async(queue2, ^{
NSLog(@"job2 in");
[NSThread sleepForTimeInterval:1.f];
NSLog(@"job2 out");
});
dispatch_async(queue1, ^{
NSLog(@"job1 in");
[NSThread sleepForTimeInterval:3.f];
NSLog(@"job1 out");
});
打印结果,可以看出直接变成串行执行了。
2018-10-22 11:20:56.532174+0800 threadTest[82086:2953839] job3 in
2018-10-22 11:20:58.532893+0800 threadTest[82086:2953839] job3 out
2018-10-22 11:20:58.533161+0800 threadTest[82086:2953839] job2 in
2018-10-22 11:20:59.538219+0800 threadTest[82086:2953839] job2 out
2018-10-22 11:20:59.538449+0800 threadTest[82086:2953839] job1 in
2018-10-22 11:21:02.542274+0800 threadTest[82086:2953839] job1 out
我们用asyn执行的代码,是异步的,如果我们想让其变为同步执行,那么就需要用到dispatch_set_target_queue