异步执行任务技术(保证应用程序的响应性能),一般将应用程序中记述的线程管理用的代码在系统级中实现。开发者只需要定义想执行的任务并追加到适当的Dispatch Queue中,GCD就能生成必要的线程并计划执行任务。
1个CPU执行的CPU命令列为一条无分叉路径,即为“线程”,即便一个CPU核虚拟为两个CPU核工作,也仍然符合一条无分叉路径的特征。
多线程的问题:数据竞争、死锁、太多线程导致消耗大量内存
dispatch_group
dispatch_queue_t queue = dispatch_queue_create("并发1", DISPATCH_QUEUE_CONCURRENT);
dispatch_queue_t queue2 = dispatch_queue_create("并发2", DISPATCH_QUEUE_CONCURRENT);
dispatch_queue_t queue3 = dispatch_queue_create("并发2", DISPATCH_QUEUE_CONCURRENT);
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group, queue, ^{
sleep(2);
NSLog(@"2");
});
dispatch_group_async(group, queue2, ^{
sleep(3);
NSLog(@"3");
});
dispatch_group_async(group, queue3, ^{
sleep(1);
NSLog(@"1");
});
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
NSLog(@"返回主线程 %@",[NSThread currentThread]);
});
dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC);
// dispatch_group_wait 会阻塞当前线程
long result = dispatch_group_wait(group, time);
if(result == 0){
NSLog(@"group整个执行结束");
}else {
// group 无法中途取消
NSLog(@"group没有执行完成 - %ld",result);
}
NSLog(@"end");
网友评论