iOS GCD使用整理
自己进行一个复习整理
1.最简单的用法
全局并行
dispatch_async(dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//code
});
2;
dispatch_queue_t queue = dispatch_queue_create("cstlab.hj", DISPATCH_QUEUE_SERIAL); //串行
dispatch_queue_t queue = dispatch_queue_create("cstlab.hj", DISPATCH_QUEUE_CONCURRENT); //并行
dispatch_async(queue, ^{ //异步
//code
});
dispatch_sync(queue, ^{ //同步
//code
});
3;延时
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//code
});
4; dispatch group
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group, queue, ^{
NSLog(@"block0-%@",[NSThread currentThread]);
});
dispatch_group_async(group, queue, ^{
NSLog(@"block1-%@",[NSThread currentThread]);
});
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
NSLog(@"block3-%@",[NSThread currentThread]);
});
5; dispatch_barrier_async
dispatch_queue_t queue = dispatch_queue_create("cstlab.hj", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(queue, ^{
NSLog(@"1---%@",[NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"2---%@",[NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"3---%@",[NSThread currentThread]);
});
dispatch_barrier_async(queue, ^{
NSLog(@"barrier---%@",[NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"4---%@",[NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"5---%@",[NSThread currentThread]);
});
6;dispatch_apply,多次执行
dispatch_apply(10, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(size_t index) {
NSLog(@"%zu-%@",index,[NSThread currentThread]);
});
7;暂停和恢复
dispatch_suspend(queue);
dispatch_resume(queue);
8; dispatch_semaphore_t
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_semaphore_t semaphore = dispatch_semaphore_create(1);
NSMutableArray *array = [NSMutableArray array];
for (NSInteger i = 0; i <= 100; i++) {
dispatch_async(queue, ^{
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
[array addObject:[NSNumber numberWithInteger:i]];
dispatch_semaphore_signal( semaphore);
});
}
9;once
static dispatch_once_t pred;
dispatch_once(&pred, ^{
//code
});
10;还有一个dispatch I/O改天介绍