概念
- 概念:全称是Grand Central Dispatch,可译为“牛逼的中枢调度器”
- 优势
– GCD是苹果公司为多核的并行运算提出的解决方案
– GCD会自动利用更多的CPU内核(比如双核、四核)
– GCD会自动管理线程的生命周期(创建线程、调度任务、销毁线程)
– 程序员只需要告诉GCD想要执行什么任务,不需要编写任何线程管理代码
任务和队列
- 核心概念
– 任务:执行什么操作
– 队列:用来存放任务 - 使用步骤
– 定制任务-确定想做的事情
– 将任务添加到队列中
- GCD会自动将队列中的任务取出,放到对应的线程中执行
- 任务的取出遵循队列的FIFO原则;先进先出,后进后出
- GCD中有两个用来执行任务的常用函数
– 用同步的方式执行任务
dispatch_sync(dispatch_queue_t queue, dispatch_block_t block);//queue:队列,block:任务
– 用异步的方式执行任务
dispatch_async(dispatch_queue_t queue, dispatch_block_t block);
- 同步和异步的区别
– 同步:只能在当前线程中执行任务,不具备开启新线程的能力
– 异步:可以在新的线程中执行任务,具备开启新线程的能力 - GCD的队列可以分为2大类型
– 并发队列(Concurrent Dispatch Queue): 可以让多个任务并发(同时)执行(自动开启多个线程同时执行任务);并发功能只有在异步(dispatch_async)函数下才有效
– 串行队列(Serial Dispatch Queue): 让任务一个接一个地执行(一个任务执行完毕后,再执行下一个任务) - 容易混淆的术语
- 有四个属于比较容易混淆:同步、异步、并发、串行
- 同步和异步主要影响:能不能开启新的线程
- 同步:只是在当前线程中执行任务,不具备开启新线程的能力
- 异步:可以在新的线程中执行任务,具备开启新线程的能力
- 并发和串行的主要影响:任务的执行方式
- 并发:允许多个任务并发(同时)执行
- 串行:一个任务执行完毕后,再执行下一个任务
并发队列
– 使用dispatch_queue_creat函数创建队列
dispatch_queue_t ;
dispatch_queue_create(const char *label,//队列名称
dispatch_queue_attr_t attr);//队列的类型
– 代码示例 并发+串行
//创建并发队列
dispatch_queue_t queue = dispatch_queue_create("com.520it.queue", DISPATCH_QUEUE_CONCURRENT);
//将任务加入队列
dispatch_async(queue, ^{
for (int i = 0 ; i<10; i++) {
NSLog(@"1----%@",[NSThread currentThread]);
}
});
dispatch_async(queue, ^{
for (int i = 0 ; i<10; i++) {
NSLog(@"2----%@",[NSThread currentThread]);
}
});
});
– GCD默认已经提供了全局的并发队列,供整个应用使用,可以无需手动创建
– 使用dispatch_get_global_queue函数获得全局的并发队列
dispatch_get_global_queue(dispatch_queue_priority_t priority,//队列的优先级
unsigned long flags);//此参数暂时无用,用0即可 dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
– 代码示例 同步函数+并发队列(不会开启新的线程)(在主线程,顺序执行)
//1、获得全局的并发队列
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//2、将任务加入队列
dispatch_sync(queue, ^{
for (int i = 0 ; i<10; i++) {
NSLog(@"1----%@",[NSThread currentThread]);
}
});
dispatch_sync(queue, ^{
for (int i = 0 ; i<10; i++) {
NSLog(@"2----%@",[NSThread currentThread]);
}
});
– 代码示例 异步函数+串行队列(会开启新的线程,但是任务是串行的,执行完一个任务,再执行下一个任务)(只开了一条子线程,顺序执行)
//1、创建串行队列
dispatch_queue_t queue = dispatch_queue_create("com.520it.queue", DISPATCH_QUEUE_SERIAL);
// dispatch_queue_t queue = dispatch_queue_create("com.520it.queue", NULL);
//2、将任务加入队列
dispatch_async(queue, ^{
for (int i = 0 ; i<10; i++) {
NSLog(@"1----%@",[NSThread currentThread]);
}
});
dispatch_async(queue, ^{
for (int i = 0 ; i<10; i++) {
NSLog(@"2----%@",[NSThread currentThread]);
}
});
– 代码示例 同步+串行(不会开启新的线程,在当前线程执行任务,任务是串行的,执行完一个任务,在执行下一个任务)(在主线程,顺序执行)
dispatch_queue_t queue = dispatch_queue_create("com.520it.queue", DISPATCH_QUEUE_SERIAL);
dispatch_sync(queue, ^{
for (int i = 0 ; i<10; i++) {
NSLog(@"1----%@",[NSThread currentThread]);
}
});
dispatch_sync(queue, ^{
for (int i = 0 ; i<10; i++) {
NSLog(@"2----%@",[NSThread currentThread]);
}
});
串行队列
- GCD 中获得串行有两种途径:
- 使用dispatch_queue_create函数创建串行队列
– 创建串行队列(队列类型传递NULL或者DISPATCH_QUEUE_SERIAL)
dispatch_queue_t queue = dispatch_queue_creat("com.520it.queue",NULL)
- 使用主队列(跟主线程相关联的队列)。
– 主队列是GCD自带的一种特殊的串行队列
– 放在主队列中的任务,都会被放到主线程中执行
– 使用dispatch_get_main_queue()获取主队列
– 代码示例 主队列+异步(在主线程,顺序执行)
dispatch_queue_t queue = dispatch_get_main_queue();
dispatch_async(queue, ^{
for (int i = 0 ; i<10; i++) {
NSLog(@"1----%@",[NSThread currentThread]);
}
});
dispatch_async(queue, ^{
for (int i = 0 ; i<10; i++) {
NSLog(@"2----%@",[NSThread currentThread]);
}
});
//异步,所以该组代码执行完毕,才会去执行async内的代码
– 代码示例 主队列+同步(在同一个队列里,同步套同步,是无法执行的。除非当前执行的代码没有在主队列中)(无法执行)
dispatch_queue_t queue = dispatch_get_main_queue();
dispatch_sync(queue, ^{
for (int i = 0 ; i<10; i++) {
NSLog(@"1----%@",[NSThread currentThread]);
}
});
dispatch_sync(queue, ^{
for (int i = 0 ; i<10; i++) {
NSLog(@"2----%@",[NSThread currentThread]);
}
});
//同步,所以是自上往下顺序执行的
– 代码示例 另外一个无法执行的情境
dispatch_queue_t queue = dispatch_queue_create("com.520it.queue", DISPATCH_QUEUE_SERIAL);
dispatch_sync(queue, ^{
NSLog(@"1----%@",[NSThread currentThread]);
dispatch_sync(queue, ^{
NSLog(@"2----%@",[NSThread currentThread]);
});
});
- 各种队列的执行效果
- 注意:使用sync函数往当前串行队列中添加任务,会卡住当前的串行队列
线程间的通讯
- 示例代码
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//图片的网络路径
NSURL *url = [NSURL URLWithString:@"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1503992696462&di=e51b985b9790aceef17d1d8e80f9c4b8&imgtype=0&src=http%3A%2F%2Fimglf0.ph.126.net%2F1EnYPI5Vzo2fCkyy2GsJKg%3D%3D%2F2829667940890114965.jpg"];
//加载图片
NSData *data = [NSData dataWithContentsOfURL:url];
//生成图片
UIImage *image = [UIImage imageWithData:data];
//回到主线程 dispatch_async(dispatch_get_main_queue(), ^{
self.imageView.image = image;
//回到子线程 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
});
});
GCD的常用函数
- GCD中还有个用来执行任务的函数:
dispatch_barrier_async_dispatch_queue_t queue,diapatch_block_t block);
在前面的任务执行结束后它才执行,而且它后面的任务等它执行完成之后才会执行 - 这个queue不能是全局的并发队列
- 示例代码
for (int i = 0; i<10; i++) {
dispatch_queue_t queue = dispatch_queue_create("com.520it.queue", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(queue, ^{
NSLog(@"1---%@",[NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"2---%@",[NSThread currentThread]);
});
dispatch_barrier_async(queue, ^{
NSLog(@"barrier---%@",[NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"4---%@",[NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"5---%@",[NSThread currentThread]);
});
}
NSLog(@"end");
– 问:为什么不能用全局并发队列
- 延迟执行
– 调用NSObject的方法
[self performSelector:@selector(run) withObject:nil afterDelay:2.0];
– 使用GCD函数
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
});
– 使用NSTimer
[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(run) userInfo:nil repeats:NO];
–NSThread
[NSThread sleepForTimeInterval:2.0];
- 一次性代码
– 使用dispatch_once函数能保证某段代码在程序运行过程中只被执行一次
static dispatch_once_t onceToken;
dispatch_once(&onceToken,^{
//只执行一次的代码(这里面默认是线程安全的)
});
- 快速迭代
– 示例代码
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_apply(19, queue, ^(size_t index) {
NSLog(@"%ld---,%@",index,[NSThread currentThread]);
});
– 应用场景示例代码
NSFileManager *manager = [NSFileManager defaultManager];
NSString *from = @"/Users/Pactor/Desktop/from";
NSString *to = @"/Users/Pactor/Desktop/to";
NSArray *subPaths = [manager subpathsAtPath:from];
dispatch_apply(subPaths.count, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(size_t index) {
NSString *fromPath = [from stringByAppendingPathComponent:[subPaths objectAtIndex:index]];
NSString *toPath = [to stringByAppendingPathComponent:[subPaths objectAtIndex:index]];
NSError *error = [[NSError alloc]init];
[manager moveItemAtPath:fromPath toPath:toPath error:&error];
});
队列组
- 有这么一种需求
– 首先:分别异步执行两个耗时操作
– 其次:等两个异步操作都执行完毕后,在回到主线程执行操作 - 如果想要快速高效地实现上述需求,可以考虑用队列组
- 示例代码
dispatch_group_t group = dispatch_group_create();
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_group_async(group, queue, ^{
//执行1个耗时的异步操作
});
dispatch_group_async(group,queue, ^{
//执行1个耗时的异步操作
});
// dispatch_group_notify(group, dispatch_get_main_queue(), ^{
dispatch_group_notify(group,queue , ^{
//等前面的异步操作都执行完毕后,才执行这个代码
NSLog(@"");
//返回主线程
dispatch_async( dispatch_get_main_queue(), ^{
});
});
– _f
dispatch_async_f的_f是指不用block,而是用函数。比如
dispatch_async_f(dispatch_queue_t queue, NULL, dispatch_function_t work)
第三个参数是一个指向函数的指针,例如void download(void *data){ }
单例模式
- 作用
– 可以保证在程序运行过程,一个类只有一个实例,而且该实例易于供外界访问
– 从而方便地控制了实例个数,并节约系统资源 - 使用场合
– 在整个应用程序中,共享一份资源(这份资源只需要创建初始化一次) - 示例代码
#import "XXPerson.h"
@interface XXPerson () <NSCopying>
@end
@implementation XXPerson
static XXPerson *_person;
+(instancetype)allocWithZone:(struct _NSZone *)zone{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_person = [super allocWithZone:zone];
});
return _person;
}
+(instancetype)sharedPerson{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_person = [[self alloc]init];
});
return _person;
}
-(id)copyWithZone:(NSZone *)zone{
return _person;
}
@end
– 抽取代码
创建XXSingleton.h
// .h文件
#define XXSingletonH(name) + (instancetype)shared##name;
// .m文件
#define XXSingletonM(name) \
static id _instance; \
\
+(instancetype)allocWithZone:(struct _NSZone *)zone{ \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instance = [super allocWithZone:zone]; \
}); \
return _instance; \
} \
\
+(instancetype)shared##name{ \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instance = [[self alloc]init]; \
}); \
return _instance; \
} \
-(id)copyWithZone:(NSZone *)zone{ \
return _instance; \
}
//“\”表示下面一行的内容也是它的
- 应用
– 比如,登陆控制器可以设置为单例 - 只要设置成单例,这个对象永远不死。因为有强指针指向它,
static id _instace
是一个全局变量 - 不用GCD
#import "XXPerson.h"
@interface XXPerson ()<NSCopying>
@end
@implementation XXPerson
static id _instance;
+(instancetype)allocWithZone:(struct _NSZone *)zone{
@synchronized (self) {
if (_instance == nil) {
_instance = [super allocWithZone:zone];
}
}
return _instance;
}
+(instancetype)sharedInstance{
@synchronized (self) {
if (_instance == nil) {
_instance = [[self alloc]init];
}
}
return _instance;
}
-(id)copyWithZone:(NSZone *)zone{
return _instance;
}
- 注意:可以用宏,可以每个单例对象都单独实现。不能写一个父类的单例,然后继承它,这样会导致所有类的单例对象访问的都是同一个对象