GCD常用方法
2019-01-29 本文已影响0人
DPL1024
一次性代码
整个程序运行过程中只会执行一次。本身是线程安全的,可以用于实现单例模式。
内部实现原理:判断onceToken的值来决定是否执行block块的代码。
- (void)once {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
// 一次性操作
});
}
一次性代码实现单例模式
+ (instancetype)sharedManager {
static DPLManager *_instance;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance = [[DPLManager alloc] init];
});
return _instance;
}
延迟执行
可以设置需要延迟执行的任务在哪个队列中执行。
延迟执行的原理:先等待,再将任务添加到队列中。
- (void)delay {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
// 需要延迟执行的任务
});
}
定时器
开启定时器
定时器类型为dispatch_source_t,通常需要设置属性或全局变量保证对象不被释放。
- (void)tiemr {
self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(0, 0));
dispatch_source_set_timer(self.timer, DISPATCH_TIME_NOW, 2.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
dispatch_source_set_event_handler(self.timer, ^{
NSLog(@"currentThread:%@", [NSThread currentThread]);
});
dispatch_resume(self.timer);
}
关闭定时器
- (void)stopTimer {
dispatch_cancel(self.timer);
}
快速迭代
开启多条子线程,和主线程一起并发执行任务。
- (void)apply {
dispatch_apply(10, dispatch_get_global_queue(0, 0), ^(size_t index) {
NSLog(@"index:%zu, cuurentThread:%@", index, [NSThread currentThread]);
});
}
栅栏函数
执行顺序:
栅栏前面的任务并发执行 -> 执行栅栏函数 -> 栅栏后面的任务并发执行
注意:不能使用全局并发队列
- (void)barrier {
dispatch_queue_t queue = dispatch_queue_create("com.dpl.queue", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(queue, ^{
NSLog(@"1---currentThread:%@", [NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"2---currentThread:%@", [NSThread currentThread]);
});
dispatch_barrier_async(queue, ^{
NSLog(@"栅栏---currentThread:%@", [NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"3---currentThread:%@", [NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"4---currentThread:%@", [NSThread currentThread]);
});
}
队列组
队列组的实现方式:
- dispatch_group_enter(group)
- dispatch_group_leave(group)
- (void)gourp {
dispatch_group_t group = dispatch_group_create();
dispatch_queue_t queue = dispatch_queue_create("com.dpl.queue", DISPATCH_QUEUE_CONCURRENT);
dispatch_group_async(group, queue, ^{
NSLog(@"1---currentThread:%@", [NSThread currentThread]);
});
dispatch_group_async(group, queue, ^{
NSLog(@"2---currentThread:%@", [NSThread currentThread]);
});
dispatch_group_async(group, queue, ^{
NSLog(@"3---currentThread:%@", [NSThread currentThread]);
});
dispatch_group_notify(group, queue, ^{
NSLog(@"队列组执行完成---currentThread:%@", [NSThread currentThread]);
});
}