1、组:dispatch_group
多个网络请求执行完,再执行刷新
dispatch_group_t group = dispatch_group_create();
NSLog(@"开始执行");
dispatch_group_enter(group);
dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSLog(@"网络请求1");
dispatch_group_leave(group);
}) ;
dispatch_group_enter(group);
dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSLog(@"网络请求2");
dispatch_group_leave(group);
}) ;
dispatch_group_enter(group);
dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSLog(@"网络请求3");
dispatch_group_leave(group);
}) ;
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
NSLog(@"刷新界面");
});
dispatch_group_wait(group, DISPATCH_TIME_FOREVER) ;
NSLog(@"等我一下");
以上代码运行打印:
开始执行
网络请求1
网络请求2
网络请求3
等我一下
刷新界面
2、dispatch_once 通常在创建单例时使用
3、dispatch_after 延迟执行
4、dispatch_barrier_async 栅栏函数
分割异步任务
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
for (int i = 0; i< 3; i++) {
NSLog(@"任务1");
}
}) ;
dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
for (int i = 0; i< 3; i++) {
NSLog(@"任务2");
}
}) ;
dispatch_barrier_async(dyConcurrent, ^{
NSLog(@"拦一下");
});
dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
for (int i = 0; i< 3; i++) {
NSLog(@"任务3");
}
}) ;
dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
for (int i = 0; i< 3; i++) {
NSLog(@"任务4");
}
}) ;
打印结果:121212拦一下343434
5、dispatch_apply 快速遍历
6、信号量 dispatch_semaphore
可控制最大并发
dispatch_semaphore_t cacheSemphore = dispatch_semaphore_create(5);
for (int i = 0; i< 10; i++) {
dispatch_async(dispatch_queue_create("dyConcurrent1", DISPATCH_QUEUE_CONCURRENT), {
dispatch_semaphore_wait(cacheSemphore , DISPATCH_TIME_FOREVER);
NSLog(@"任务%ld",(long)i);
sleep(1);
NSLog(@"到我了");
dispatch_semaphore_signal(cacheSemphore);
});
}
打印结果:
任务0
任务1
任务2
任务3
任务4
到我了
到我了
到我了
到我了
到我了
任务5
任务6
任务7
任务8
任务9
到我了
到我了
到我了
到我了
到我了