简述
GCD (Grand Central Dispatch) ,是苹果开发的多核编程的解决方案,GCD和其他多线程方案比较起来,使用更简单方便。
使用
后台执行
dispatch_async(dispatch_get_global_queue(0, 0), ^{
});
主线程执行
dispatch_async(dispatch_get_main_queue(), ^{
});
一次性执行
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
});
延迟执行
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
});
自定义queue
dispatch_queue_t queue = dispatch_queue_create("com.queue.tt", NULL);
dispatch_async(queue, ^{
});
dispatch_release(queue);
高级用法
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group, dispatch_get_global_queue(0, 0), ^{
// task 1
});
dispatch_group_async(group, dispatch_get_global_queue(0, 0), ^{
// task 2
});
dispatch_group_notify(group, dispatch_get_global_queue(0, 0), ^{
//任务执行完成
});
后台运行
@property (assign, nonatomic) UIBackgroundTaskIdentifier ide;
- (void)beginBackTask
{
self.ide = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
}];
}
- (void)endBackTask
{
[[UIApplication sharedApplication] endBackgroundTask:self.ide];
self.ide = UIBackgroundTaskInvalid;
}
总结
总体来说GCD能够极大地方便开发者进行多线程编程
网友评论