(一)、线程的概念和与生命周期
进程:可以简单理解为进程为一个应用程序
线程:是CPU调度和分派的基本单位
下图是线程状态示意图,从图中可以看出线程的生命周期是:新建 - 就绪 - 运行 - 阻塞 - 死亡
(二)、多线程的四种解决方案
多线程的四种解决方案分别是:OC主要使用NSThread,GCD, NSOperation,pthread为跨平台的。
(三)、GCD的特点和运用场景
GCD是苹果提供的,底层为C 语言写的,一套多线程API ,它具有操作简单、执行高效特点。GCD以block为基本单位,一个block中的代码可以视为一个任务。GCD中有两大最重要的概念,分别是“队列”和“执行方式”。开发者要做的只是定义执行的任务并追加到适当的 Dispatch Queue 中。
(1)GCD术语解释
(2)GCD几种队列获取方式
- 主线程队列(The main queue):通过
dispatch_get_main_queue()
来获得,这是一个串行队列。提交至main queue的任务会在主线程中执行,app中的main函数默认在主线程执行,和UI相关的修改必须使用Main Queue。
- 全局并发队列(Global queue): 通过调用
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
函数来获取(可以设置优先级),全局并发队列由整个进程共享,有高、中(默认)、低、后台四个优先级别。
自定义队列(Custom queue):通过调用
dispatch_queue_create("test", DISPATCH_QUEUE_CONCURRENT)
来创建,DISPATCH_QUEUE_CONCURRENT并行队列,可以并发的执行多个任务,但是执行完成的顺序是随机的。DISPATCH_QUEUE_SERIAL串行队列,队列里的任务都是串行执行的,一个执行完再执行下一个。Group queue (队列组):通过调用
dispatch_group_create()
来获取将多线程进行分组,最大的好处是可获知所有线程的完成情况。 通过dispatch_group_notify
可以直接监听组里所有线程完成情况。
(3)GCD队列异步dispatch_async、同步dispatch_sync执行方式区别
(3.1)GCD常用场景一:实现多个异步线程同步操作
我们也知道异步函数 + 串行队列实现任务同步执行更加简单。
不过异步函数 + 串行队列的弊端也是非常明显的:
因为是异步函数,所以系统会开启新(子)线程,又因为是串行队列,所以系统只会开启一个子线程。
这就导致了所有的任务都是在这个子线程中同步的一个一个执行。丧失了并发执行的可能性。
虽然可以完成任务,但是却没有充分发挥CPU多核(多线程)的优势。
/*
* 同步和异步决定了是否开启新线程(或者说是否具有开启新线程的能力),
* 串行和并发决定了任务的执行方式——串行执行还是并发执行(或者说开启多少条新线程)
*/
- (void)dispatchAsyncForSerial {
dispatch_queue_t serialQueue = dispatch_queue_create("dispatchAsyncForSerial", DISPATCH_QUEUE_SERIAL);
NSMutableArray *arrayM = [NSMutableArray arrayWithCapacity:12];
for (int i = 0; i < 12; i++) {
dispatch_async(serialQueue, ^{
[arrayM addObject:[NSNumber numberWithInt:i]];
NSLog(@"currentThread = %@, %@",[NSThread currentThread],[NSNumber numberWithInt:i]);
});
}
}
输出:nunber = 5 说明开启了一个新线程在执行
currentThread = <NSThread: 0x6000036b2100>{number = 5, name = (null)}, 0
currentThread = <NSThread: 0x6000036b2100>{number = 5, name = (null)}, 1
currentThread = <NSThread: 0x6000036b2100>{number = 5, name = (null)}, 2
currentThread = <NSThread: 0x6000036b2100>{number = 5, name = (null)}, 3
currentThread = <NSThread: 0x6000036b2100>{number = 5, name = (null)}, 4
currentThread = <NSThread: 0x6000036b2100>{number = 5, name = (null)}, 5
currentThread = <NSThread: 0x6000036b2100>{number = 5, name = (null)}, 6
currentThread = <NSThread: 0x6000036b2100>{number = 5, name = (null)}, 7
currentThread = <NSThread: 0x6000036b2100>{number = 5, name = (null)}, 8
currentThread = <NSThread: 0x6000036b2100>{number = 5, name = (null)}, 9
currentThread = <NSThread: 0x6000036b2100>{number = 5, name = (null)}, 10
currentThread = <NSThread: 0x6000036b2100>{number = 5, name = (null)}, 11
- Dispatch Semaphore 信号量:
1: 用GCD的信号量来实现异步线程同步操作
2: 保证线程安全,为线程加锁
/*
*1.dispatch_semaphore_create:创建一个Semaphore并初始化信号的总量
* 2.dispatch_semaphore_signal:发送一个信号,让信号总量加1
* 3.dispatch_semaphore_wait:可以使总信号量减1,当信号总量为0时就会一直等待(阻塞所在线程),否则就可以正常执行。
*/
//MARK: - 用GCD的信号量来实现异步线程同步操作 1:同步且并发执行发挥多核优势 2:保证线程安全,为线程加锁
- (void)dispatchSemaphore {
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
NSMutableArray *arrayM = [NSMutableArray arrayWithCapacity:12];
// 创建为1的信号量
dispatch_semaphore_t sem = dispatch_semaphore_create(1);
for (int i = 0; i < 12; i++) {
dispatch_async(queue, ^{
// 等待信号量
dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
[arrayM addObject:[NSNumber numberWithInt:i]];
NSLog(@"currentThread = %@, %@",[NSThread currentThread],[NSNumber numberWithInt:i]);
// 发送信号量
dispatch_semaphore_signal(sem);
});
}
}
输出:在多个线程下并发执行完任务
currentThread = <NSThread: 0x600002db7280>{number = 5, name = (null)}, 0
currentThread = <NSThread: 0x600002df9480>{number = 6, name = (null)}, 2
currentThread = <NSThread: 0x600002dfa940>{number = 7, name = (null)}, 1
currentThread = <NSThread: 0x600002da3180>{number = 8, name = (null)}, 3
currentThread = <NSThread: 0x600002dc95c0>{number = 4, name = (null)}, 4
currentThread = <NSThread: 0x600002db8280>{number = 3, name = (null)}, 5
currentThread = <NSThread: 0x600002df9500>{number = 9, name = (null)}, 6
currentThread = <NSThread: 0x600002dfa7c0>{number = 10, name = (null)}, 7
currentThread = <NSThread: 0x600002db7280>{number = 5, name = (null)}, 9
currentThread = <NSThread: 0x600002da37c0>{number = 11, name = (null)}, 8
currentThread = <NSThread: 0x600002da4f40>{number = 12, name = (null)}, 10
currentThread = <NSThread: 0x600002da5080>{number = 13, name = (null)}, 11
(3.2)GCD常用场景二:dispatch_barrier_sync实现多读单写
/* 实现多读单写
* 这里的dispatch_barrier_sync上的队列要和需要阻塞的任务在同一队列上,否则是无效的。
* 栅栏函数任务:在他之前所有的任务执行完毕,并且在它后面的任务开始之前,期间不会有其他的任务执行,这样比较好的促使 写操作一个接一个写 (写写互斥),不会乱!
* 运用对NSMutableArray 多读单写保证线程安全
*/
//MARK: - 实现多读单写
-(void)dispatchBarrier {
[self setObject:@"hello kitty" forKey:@"message" waitTime:4];
for (NSInteger i = 0; i < 10; i++) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self valueForKey:@"message"];
});
}
NSLog(@"写操作hello kitty后的任务");
[self setObject:@"hello jack" forKey:@"message" waitTime:2];
for (NSInteger i = 0; i < 10; i++) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self valueForKey:@"message"];
});
}
NSLog(@"写操作hello jack后的任务");
[self setObject:@"hello weilian" forKey:@"message" waitTime:3];
for (NSInteger i = 0; i < 10; i++) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self valueForKey:@"message"];
});
}
NSLog(@"写操作hello weilian后的任务");
}
- (id)valueForKey:(NSString *)key {
id __block obj;
// 在调用此函数的线程同步执行所有添加到 queue 队列的读任务,
// 如果前边有写的任务, 由于 barrier 堵塞队列, 只能等待写任务完成
dispatch_sync(_dictQueue, ^{
obj = [self.dict valueForKey:key];
NSLog(@"read thread = %@, %@",[NSThread currentThread],obj);
});
return obj;
}
- (void)setObject:(id)obj forKey:(id<NSCopying>)key waitTime:(int)sleepNum {
// 重点:dispatch_barrier_async(),异步栅栏调用;栅栏函数堵塞的是队列,添加到队列中的写操作任务, 只能依次按照添加顺序进行修改,不会出现资源抢夺现象
// 在子线程完成写任务,因为顺序执行只需要开辟一个线程
// 等待前面任务执行完成后开始写
// 写的完成任务后, 才能继续执行后边添加进此队列的任务
dispatch_barrier_async(_dictQueue, ^{
sleep(sleepNum); //模拟耗时操作
[self.dict setObject:obj forKey:key];
NSLog(@"write thread = %@, %@",[NSThread currentThread],obj);
});
}
输出:
- 先打印初nslog 的日志,dispatch_barrier_async使用并发且不堵塞当前线程(当前主线程),
- 我们可以看到 三个写操作虽然他们耗时不同,但都按照入队的顺序依次执行,hello kitty-> hello jack-> hello weilian
- 后面打印20来个 hello weilian 是因为 在读的过程中有插入写的任务,只有等 dispatch_barrier_async()执行完才能执行后边添加进此队列读任务
写操作hello kitty后的任务
写操作hello jack后的任务
写操作hello weilian后的任务
write thread = <NSThread: 0x600000ea2600>{number = 5, name = (null)}, hello kitty
read thread = <NSThread: 0x600000ec6580>{number = 2, name = (null)}, hello kitty
read thread = <NSThread: 0x600000ec74c0>{number = 7, name = (null)}, hello kitty
read thread = <NSThread: 0x600000ec1000>{number = 3, name = (null)}, hello kitty
read thread = <NSThread: 0x600000ee4ac0>{number = 9, name = (null)}, hello kitty
read thread = <NSThread: 0x600000edc5c0>{number = 10, name = (null)}, hello kitty
write thread = <NSThread: 0x600000edc5c0>{number = 10, name = (null)}, hello jack
read thread = <NSThread: 0x600000ed7980>{number = 11, name = (null)}, hello jack
read thread = <NSThread: 0x600000ee0040>{number = 12, name = (null)}, hello jack
read thread = <NSThread: 0x600000ed5300>{number = 13, name = (null)}, hello jack
write thread = <NSThread: 0x600000ee0040>{number = 12, name = (null)}, hello weilian
read thread = <NSThread: 0x600000ee0140>{number = 14, name = (null)}, hello weilian
read thread = <NSThread: 0x600000edd340>{number = 17, name = (null)}, hello weilian
read thread = <NSThread: 0x600000ed2540>{number = 16, name = (null)}, hello weilian
read thread = <NSThread: 0x600000ee02c0>{number = 15, name = (null)}, hello weilian
read thread = <NSThread: 0x600000ee00c0>{number = 18, name = (null)}, hello weilian
read thread = <NSThread: 0x600000ed25c0>{number = 20, name = (null)}, hello weilian
read thread = <NSThread: 0x600000ede000>{number = 21, name = (null)}, hello weilian
read thread = <NSThread: 0x600000ee4680>{number = 19, name = (null)}, hello weilian
read thread = <NSThread: 0x600000ee4980>{number = 23, name = (null)}, hello weilian
read thread = <NSThread: 0x600000ed2640>{number = 24, name = (null)}, hello weilian
read thread = <NSThread: 0x600000ee0240>{number = 22, name = (null)}, hello weilian
read thread = <NSThread: 0x600000ed2680>{number = 27, name = (null)}, hello weilian
read thread = <NSThread: 0x600000ede100>{number = 25, name = (null)}, hello weilian
read thread = <NSThread: 0x600000ee0300>{number = 26, name = (null)}, hello weilian
read thread = <NSThread: 0x600000ed2700>{number = 29, name = (null)}, hello weilian
read thread = <NSThread: 0x600000ee46c0>{number = 28, name = (null)}, hello weilian
read thread = <NSThread: 0x600000ee4740>{number = 31, name = (null)}, hello weilian
read thread = <NSThread: 0x600000edc600>{number = 30, name = (null)}, hello weilian
read thread = <NSThread: 0x600000ee47c0>{number = 32, name = (null)}, hello weilian
read thread = <NSThread: 0x600000ede1c0>{number = 33, name = (null)}, hello weilian
read thread = <NSThread: 0x600000ede140>{number = 35, name = (null)}, hello weilian
read thread = <NSThread: 0x600000ee0340>{number = 34, name = (null)}, hello weilian
(3.3)GCD常用场景三:dispatch_group实现多个网络请求的同步问题
/**dispatch_group 可以实现监听一组任务是否完成,完成后得到通知执行其他的操作
* dispatch_group_enter标志着一个任务追加到 group,执行一次,相当于 group 中未执行完毕任务数+1
* dispatch_group_leave标志着一个任务离开了 group,执行一次,相当于 group 中未执行完毕任务数-1。
* 用dispatch_async(queue, ^{})则必须配合enter和level才能最后执行notify;用dispatch_group_async来提交任务如果是异步的,也必须配合enter和level,
* 当 group 中未执行完毕任务数为0的时候,才会使dispatch_group_wait解除阻塞,以及执行追加到dispatch_group_notify中的任务。
*/
- (void)dispatch_group_test {
NSLog(@"group---begin");
dispatch_group_t group = dispatch_group_create();
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//A1耗时操作
dispatch_group_enter(group);
dispatch_async(queue, ^{
sleep(1.5);
NSLog(@"A1耗时操作---%@",[NSThread currentThread]);
dispatch_group_leave(group);
});
//A2耗时操作
dispatch_group_async(group, queue, ^{
sleep(3);
NSLog(@"A2耗时操作---%@",[NSThread currentThread]);
});
//B网络请求
dispatch_group_enter(group);
dispatch_group_async(group, queue, ^{
sleep(4);
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"B网络请求---%@",[NSThread currentThread]);
dispatch_group_leave(group);
});
});
//C网络请求
dispatch_group_enter(group);
dispatch_group_async(group, queue, ^{
sleep(2);
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"C网络请求---%@",[NSThread currentThread]);
dispatch_group_leave(group);
});
});
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
//等前面的异步操作都执行完毕后,回到主线程.
//模拟耗时操作
sleep(1);
//打印当前线程
NSLog(@"group---end---%@",[NSThread currentThread]);
});
NSLog(@"code end");
}
输出:
group---begin
code end
A1耗时操作---<NSThread: 0x60000293dc40>{number = 5, name = (null)}
C网络请求---<NSThread: 0x600002934740>{number = 1, name = main}
A2耗时操作---<NSThread: 0x60000297e9c0>{number = 6, name = (null)}
B网络请求---<NSThread: 0x600002934740>{number = 1, name = main}
group---end---<NSThread: 0x600002934740>{number = 1, name = main}
总结:
- dispatch_group是一个初始值为LONG_MAX的信号量,group中的任务完成是判断其value是否恢复成初始值。
- dispatch_group_enter和dispatch_group_leave必须成对使用并且支持嵌套。
- 如果dispatch_group_enter比dispatch_group_leave多,由于value不等于dsema_orig不会走到唤醒逻辑,dispatch_group_notify中的任务无法执行或者dispatch_group_wait收不到信号而卡住线程。
- 如果是dispatch_group_leave多,则会引起崩溃。
(3.4)GCD造成主线死锁的情况
/*
* 1、主队列同步任务,造成相互等待,死锁
* 2、串行队列(同步/异步任务)嵌套同步任务,造成相互等待,死锁
*/
- (void)deathLock {
//1、主队列同步任务,造成相互等待,死锁
dispatch_sync(dispatch_get_main_queue(), ^{
NSLog(@"deallock");
});
//2、串行队列(同步/异步任务)嵌套同步任务,造成相互等待,死锁
dispatch_queue_t serialQueue = dispatch_queue_create("test", DISPATCH_QUEUE_SERIAL);
dispatch_async(serialQueue, ^{
dispatch_sync(serialQueue, ^{
NSLog(@"deadlock");
});
});
}