dispatch_set_target_queue
利用dispatch_queue_create生成的函数的优先级都是'默认优先级'。但是想要改变优先级就需要用到这个函数:dispatch_set_target_queue。dispatch_set_target_queue不仅可以改变优先级,还可以改变执行层次.
dispatch_queue_t serialQueue = dispatch_queue_create("com.test", NULL);
dispatch_queue_t globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
// serial的优先级 == globalQueue的优先级
dispatch_set_target_queue(serial, globalQueue);
解决多个Serial Dispatch Queue并行执行
当一个任务被分为ABCD的时候,还需要他们串行执行,就需要dispatch_set_target_queue来帮助实现.如下:
dispatch_queue_t serialQueue = dispatch_queue_create("com.test", DISPATCH_QUEUE_SERIAL);
dispatch_queue_t serialQueue2 = dispatch_queue_create("com.test2", DISPATCH_QUEUE_SERIAL);
dispatch_queue_t serialQueue3 = dispatch_queue_create("com.test3", DISPATCH_QUEUE_SERIAL);
dispatch_queue_t serialQueue4 = dispatch_queue_create("com.test4", DISPATCH_QUEUE_SERIAL);
dispatch_queue_t serialQueue5 = dispatch_queue_create("com.test5", DISPATCH_QUEUE_SERIAL);
dispatch_set_target_queue(serialQueue2, serialQueue);
dispatch_set_target_queue(serialQueue3, serialQueue);
dispatch_set_target_queue(serialQueue4, serialQueue);
dispatch_set_target_queue(serialQueue5, serialQueue);
dispatch_sync(serialQueue2, ^{
NSLog(@"2000000");
[NSThread sleepForTimeInterval:3];
NSLog(@"20000001");
});
dispatch_sync(serialQueue3, ^{
NSLog(@"300000");
[NSThread sleepForTimeInterval:2];
NSLog(@"30000001");
});
dispatch_sync(serialQueue4, ^{
NSLog(@"40000000");
[NSThread sleepForTimeInterval:2.5];
NSLog(@"40000001");
});
dispatch_sync(serialQueue5, ^{
NSLog(@"5000000");
[NSThread sleepForTimeInterval:1];
NSLog(@"50000001");
});
执行结果:
dispatch_after
这个应该够很熟悉了,使用场景就是,你想在3秒后进行此操作,就可以通过该函数来实现。
🐷:此处的3秒不是在3秒后执行,而是在3秒后追加Block到Dispatch Queue中。
dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, 3*NSEC_PER_SEC);
dispatch_after(time, dispatch_get_main_queue(), ^{
NSLog(@"汪汪汪...");
});
Dispatch Group
当多个执行处理完成后我们想执行结束处理,这种情况应该怎么办呢?
答:就serial dispatch queue 来说,在它的最后追加结束处理即可。但是使用Concurrent Dispatch Queue或者同时使用多个的时候,想要执行结束处理,就会有点难。。。。
啧啧啧!!!我们可以使用Dispatch Group:
dispatch_group_t group = dispatch_group_create();
dispatch_queue_t queue = dispatch_queue_create("com.test", DISPATCH_QUEUE_CONCURRENT);
dispatch_group_async(group, queue, ^{NSLog(@"12345");});
dispatch_group_async(group, queue, ^{NSLog(@"1234567");});
dispatch_group_async(group, queue, ^{NSLog(@"123456789");});
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
NSLog(@"over...");
});
*注意:
无论向什么样的Dispatch Queue中追加block,'dispatch_group_notify'都会最后(在所有任务处理完成)执行。
执行结果:
2016-07-07 14:16:17.092 多线程之GCD[14481:166110] 12345
2016-07-07 14:16:17.092 多线程之GCD[14481:166139] 123456789
2016-07-07 14:16:17.092 多线程之GCD[14481:166116] 1234567
2016-07-07 14:16:17.433 多线程之GCD[14481:165974] over...
网友评论