iOS - 多线程(一):初识
iOS - 多线程(二):pthread、NSThread
iOS - 多线程(三):GCD
iOS - 多线程(四):NSOperation
iOS - 多线程(五):线程同步方案
多线程方案 | 区别 |
---|---|
GCD | GCD 是 iOS4.0 推出的,主要针对多核 CPU 做了优化,是 C 语言的技术; GCD 是将任务(block)添加到队列(串行/并发/全局/主队列),并且以同步/异步的方式执行任务的函数; GCD 提供了一些 NSOperation 不具备的功能: ① 队列组 ② 一次性执行 ③ 延迟执行 |
NSOperation | NSOperation 是 iOS2.0 推出的,iOS4 之后重写了 NSOperation; NSOperation 是将操作(异步的任务)添加到队列(并发队列),就会执行指定操作的函数; NSOperation 里提供的方便的操作: ① 最大并发数 ② 队列的暂停/继续/取消操作 ③ 指定操作之间的依赖关系(GCD 中可以使用同步实现) |
NSOperation 需要和 NSOperationQueue 配合使用来实现多线程方案。单独使用 NSOperation 的话, 它是属于同步操作, 并不具备开启新线程的能力。
NSOperation:操作
NSOperationQueue:队列
获取主队列:[NSOperationQueue mainQueue]
获取当前队列:[NSOperationQueue currentQueue]
NSOperation 和 NSOperationQueue 实现多线程的步骤:
往队列中添加操作:
- (void)addOperation:(NSOperation *)op;
- (void)addOperations:(NSArray<NSOperation *> *)ops waitUntilFinished:(BOOL)wait;
- (void)addOperationWithBlock:(void (^)(void))block
如果不想使用 NSOperationQueue,可以通过调用 NSOperation 对象的start
方法来自己执行操作。默认情况下,调用 NSOperation 的 start 方法并不会开一条新线程去执行操作,而是在当前线程同步执行操作。
默认情况下,调用 NSOperation 的 start 方法后并不会开一条新线程去执行操作,而是在当前线程同步执行操作。
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
// 创建一个 NSInvocationOperation 对象
NSInvocationOperation *operation = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(test) object:nil];
// 调用 start 方法开始执行操作,一旦执行操作,就会调用 target 的 sel 方法
[operation start];
}
- (void)test {
NSLog(@"%@",[NSThread currentThread]);
}
/*
2020-01-20 09:34:21.163313+0800 多线程[28423:6280457] {number = 1, name = main}
*/
只有将 NSOperation 放到一个 NSOperationQueue 中,才会异步执行操作。
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
// 创建一个 NSOperationQueue 对象
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
// 创建一个 NSInvocationOperation 对象
NSInvocationOperation *operation = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(test) object:nil];
// 将操作添加进队列
[queue addOperation:operation];
}
- (void)test {
NSLog(@"%@",[NSThread currentThread]);
}
/*
2020-01-20 09:36:06.327162+0800 多线程[28423:6280510] {number = 7, name = (null)}
*/
注意点: 如果将操作添加到队列后,又调用 start 方法,会导致Crash
。
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
NSInvocationOperation *operation = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(test) object:nil];
[queue addOperation:operation];
[operation start];
}
- (void)test {
NSLog(@"%@",[NSThread currentThread]);
}
/*
2020-02-03 03:49:07.027372+0800 多线程[11489:1903781] {number = 3, name = (null)}
2020-02-03 03:49:07.031612+0800 多线程[11489:1903644] *** Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: '*** -[NSInvocationOperation start]: something is trying to start the receiver simultaneously from more than one thread'
*** First throw call stack:
(
0 CoreFoundation 0x00007fff23b98bde __exceptionPreprocess + 350
1 libobjc.A.dylib 0x00007fff503b5b20 objc_exception_throw + 48
2 Foundation 0x00007fff25653930 -[NSOperation start] + 1424
......
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)
*/
三种方法
// 方法一:调用start,不会开启新线程,在当前线程同步执行
- (void)demo1 {
NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"%@",[NSThread currentThread]);
}];
[operation start];
}
//2020-01-20 09:55:12.698046+0800 多线程[28530:6301526] {number = 1, name = main}
// 方法二:创建 NSOperationQueue 添加进队列
- (void)demo2 {
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"%@",[NSThread currentThread]);
}];
[queue addOperation:operation];
}
//2020-01-20 09:55:32.941607+0800 多线程[28530:6301710] {number = 6, name = (null)}
// 方法三:调用队列的 addOperationWithBlock 方法
- (void)demo3 {
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
[queue addOperationWithBlock:^{
NSLog(@"%@",[NSThread currentThread]);
}];
}
//2020-01-20 09:55:42.465422+0800 多线程[28530:6301710] {number = 6, name = (null)}
异步并发:
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
for (int i = 0; i < 5; i++) {
[queue addOperationWithBlock:^{
NSLog(@"%@",[NSThread currentThread]);
}];
}
/*
2020-01-20 10:16:08.266873+0800 多线程[28609:6320429] {number = 3, name = (null)}
2020-01-20 10:16:08.266960+0800 多线程[28609:6321076] {number = 8, name = (null)}
2020-01-20 10:16:08.267151+0800 多线程[28609:6321077] {number = 9, name = (null)}
2020-01-20 10:16:08.268080+0800 多线程[28609:6320429] {number = 3, name = (null)}
2020-01-20 10:16:08.267340+0800 多线程[28609:6321078] {number = 10, name = (null)}
*/
添加执行代码块:
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"%@",[NSThread currentThread]);
}];
[operation addExecutionBlock:^{
NSLog(@"执行任务1,%@",[NSThread currentThread]);
}];
[operation addExecutionBlock:^{
NSLog(@"执行任务2,%@",[NSThread currentThread]);
}];
[operation addExecutionBlock:^{
NSLog(@"执行任务3,%@",[NSThread currentThread]);
}];
[queue addOperation:operation];
/*
2020-02-03 16:12:15.262259+0800 多线程[11894:2041391] {number = 5, name = (null)}
2020-02-03 16:12:15.262491+0800 多线程[11894:2041394] 执行任务1,{number = 3, name = (null)}
2020-02-03 16:12:15.262575+0800 多线程[11894:2041399] 执行任务2,{number = 8, name = (null)}
2020-02-03 16:12:15.262653+0800 多线程[11894:2041471] 执行任务3,{number = 9, name = (null)}
*/
完成后回调,是在子线程上执行,所以不能用来更新 UI:
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"hello,%@",[NSThread currentThread]);
}];
[operation setCompletionBlock:^{
NSLog(@"end,%@",[NSThread currentThread]);
}];
[queue addOperation:operation];
/*
2020-01-20 10:16:42.333300+0800 多线程[28609:6321079] hello,{number = 11, name = (null)}
2020-01-20 10:16:42.333687+0800 多线程[28609:6321079] end,{number = 11, name = (null)}
*/
模拟图片下载完成后回到主线程更新 UI:
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
[queue addOperationWithBlock:^{
NSLog(@"下载图片,%@",[NSThread currentThread]);
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
NSLog(@"下载完成更新UI,%@",[NSThread currentThread]);
}];
}];
/*
2020-01-20 10:32:55.807874+0800 多线程[28682:6334587] 下载图片,{number = 5, name = (null)}
2020-01-20 10:32:55.808920+0800 多线程[28682:6334435] 下载完成更新UI,{number = 1, name = main}
*/
@property NSInteger maxConcurrentOperationCount;
// 控制最大并发数为2
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
queue.maxConcurrentOperationCount = 2;
for (int i = 0; i < 6; i++) {
[queue addOperationWithBlock:^{
sleep(1);
NSLog(@"%@",[NSThread currentThread]);
}];
}
/*
2020-01-20 11:04:07.401515+0800 多线程[28747:6348715] {number = 9, name = (null)}
2020-01-20 11:04:07.401415+0800 多线程[28747:6359523] {number = 8, name = (null)}
2020-01-20 11:04:08.407240+0800 多线程[28747:6348709] {number = 6, name = (null)}
2020-01-20 11:04:08.407238+0800 多线程[28747:6359523] {number = 8, name = (null)}
2020-01-20 11:04:09.411438+0800 多线程[28747:6359523] {number = 8, name = (null)}
2020-01-20 11:04:09.411820+0800 多线程[28747:6359537] {number = 10, name = (null)}
*/
/*
NSOperationQueue
*/
// YES:暂停 / NO:继续(当前正在执行的操作会执行完毕,暂停后续的所有操作)
@property (getter=isSuspended) BOOL suspended;
// 取消队列中的所有操作(当前正在执行的操作会执行完毕,取消后续的所有操作)
- (void)cancelAllOperations;
/*
NSOperation
*/
// 也可以调用 NSOperation 的 cancel 方法移除单个操作
- (void)cancel;
- (IBAction)start:(id)sender {
self.queue = [[NSOperationQueue alloc]init];
self.queue.maxConcurrentOperationCount = 1;
NSLog(@"开始");
for (int i = 0; i < 10; i++) {
[self.queue addOperationWithBlock:^{
sleep(1);
NSLog(@"操作%d,%@",i,[NSThread currentThread]);
}];
}
}
- (IBAction)suspend:(id)sender {
self.queue.suspended = YES;
NSLog(@"暂停");
}
- (IBAction)resume:(id)sender {
self.queue.suspended = NO;
NSLog(@"继续");
}
- (IBAction)cancel:(id)sender {
[self.queue cancelAllOperations];
NSLog(@"取消");
}
/*
2020-01-20 19:40:36.128809+0800 多线程[29051:6389455] 开始
2020-01-20 19:40:37.133303+0800 多线程[29051:6389765] 操作0,{number = 8, name = (null)}
2020-01-20 19:40:38.138239+0800 多线程[29051:6520475] 操作1,{number = 9, name = (null)}
2020-01-20 19:40:39.142707+0800 多线程[29051:6389765] 操作2,{number = 8, name = (null)}
2020-01-20 19:40:39.804264+0800 多线程[29051:6389455] 暂停
2020-01-20 19:40:40.145399+0800 多线程[29051:6520475] 操作3,{number = 9, name = (null)}
2020-01-20 19:40:45.175465+0800 多线程[29051:6389455] 继续
2020-01-20 19:40:46.179761+0800 多线程[29051:6520475] 操作4,{number = 9, name = (null)}
2020-01-20 19:40:47.184917+0800 多线程[29051:6520585] 操作5,{number = 10, name = (null)}
2020-01-20 19:40:48.189422+0800 多线程[29051:6520585] 操作6,{number = 10, name = (null)}
2020-01-20 19:40:49.192921+0800 多线程[29051:6520475] 操作7,{number = 9, name = (null)}
2020-01-20 19:40:49.748142+0800 多线程[29051:6389455] 取消
2020-01-20 19:40:50.198083+0800 多线程[29051:6520585] 操作8,{number = 10, name = (null)}
*/
操作的执行状态:
@property (readonly, getter=isReady) BOOL ready; //就绪
@property (readonly, getter=isExecuting) BOOL executing; //正在执行
@property (readonly, getter=isFinished) BOOL finished; //完成
@property (readonly, getter=isCancelled) BOOL cancelled; //取消
怎么控制 NSOperation 的状态?
main
方法,底层控制变更操作执行完成状态,以及操作退出;start
方法,自行控制任务状态。系统是怎样移除一个isFinished = YES
的 NSOperation 的?
答案:通过KVO
。
可以通过NSOperation 的queuePriority
属性来设置操作在队列中的执行优先级
typedef NS_ENUM(NSInteger, NSOperationQueuePriority) {
NSOperationQueuePriorityVeryLow = -8L,
NSOperationQueuePriorityLow = -4L,
NSOperationQueuePriorityNormal = 0,
NSOperationQueuePriorityHigh = 4,
NSOperationQueuePriorityVeryHigh = 8
};
@property NSOperationQueuePriority queuePriority;
可以通过NSOperation 的qualityOfService
属性来设置操作在队列中的服务质量(iOS8 以后苹果推荐使用服务质量替代优先级)
typedef NS_ENUM(NSInteger, NSQualityOfService) {
NSQualityOfServiceUserInteractive = 0x21,
NSQualityOfServiceUserInitiated = 0x19,
NSQualityOfServiceUtility = 0x11,
NSQualityOfServiceBackground = 0x09,
NSQualityOfServiceDefault = -1
}
@property NSQualityOfService qualityOfService;
示例:
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
NSBlockOperation *op1 = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"执行任务1,%@",[NSThread currentThread]);
}];
NSBlockOperation *op2 = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"执行任务2,%@",[NSThread currentThread]);
}];
NSBlockOperation *op3 = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"执行任务3,%@",[NSThread currentThread]);
}];
//设置优先级
op1.queuePriority = NSOperationQueuePriorityLow;
op2.queuePriority = NSOperationQueuePriorityHigh;
op3.queuePriority = NSOperationQueuePriorityNormal;
//将操作加入队列
[queue addOperations:[NSArray arrayWithObjects:op1, op2, op3, nil] waitUntilFinished:YES];
/*
2020-01-20 20:01:03.451992+0800 多线程[29529:6537872] 执行任务2,{number = 3, name = (null)}
2020-01-20 20:01:03.452049+0800 多线程[29529:6539534] 执行任务3,{number = 8, name = (null)}
2020-01-20 20:01:03.452057+0800 多线程[29529:6539535] 执行任务1,{number = 9, name = (null)}
*/
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
NSBlockOperation *op1 = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"执行任务1,%@",[NSThread currentThread]);
}];
NSBlockOperation *op2 = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"执行任务2,%@",[NSThread currentThread]);
}];
NSBlockOperation *op3 = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"执行任务3,%@",[NSThread currentThread]);
}];
//设置服务质量
op1.qualityOfService = NSQualityOfServiceBackground;
op2.qualityOfService = NSQualityOfServiceUserInitiated;
op3.qualityOfService = NSQualityOfServiceUtility;
//将操作加入队列
[queue addOperations:[NSArray arrayWithObjects:op1, op2, op3, nil] waitUntilFinished:YES];
/*
2020-01-20 20:01:44.482371+0800 多线程[29558:6540419] 执行任务2,{number = 6, name = (null)}
2020-01-20 20:01:44.482387+0800 多线程[29558:6540420] 执行任务3,{number = 7, name = (null)}
2020-01-20 20:01:44.482371+0800 多线程[29558:6540425] 执行任务1,{number = 3, name = (null)}
*/
NSOperation 之间可以通过以下方法添加/移除依赖来保证执行顺序。
// 添加操作间依赖
- (void)addDependency:(NSOperation *)op;
// 移除操作间依赖
- (void)removeDependency:(NSOperation *)op;
比如一定要操作 A 执行完后再执行操作 B,可以这样写:
注意点: 不能相互依赖,如 B 依赖于 A,A 依赖于 B。
[operationB addDependency:operationA]; // 操作B 依赖于 操作A
示例: B依赖A,A依赖C(CAB)
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
NSBlockOperation *opA = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"执行任务A,%@",[NSThread currentThread]);
}];
NSBlockOperation *opB = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"执行任务B,%@",[NSThread currentThread]);
}];
NSBlockOperation *opC = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"执行任务C,%@",[NSThread currentThread]);
}];
//添加依赖关系
[opB addDependency:opA];
[opA addDependency:opC];
//将操作加入队列
[queue addOperations:[NSArray arrayWithObjects:opA, opB, opC, nil] waitUntilFinished:YES];
/*
2020-01-20 20:26:01.717558+0800 多线程[29650:6556372] 执行任务C,{number = 3, name = (null)}
2020-01-20 20:26:01.718132+0800 多线程[29650:6556372] 执行任务A,{number = 3, name = (null)}
2020-01-20 20:26:01.721032+0800 多线程[29650:6560162] 执行任务B,{number = 8, name = (null)}
*/
可以在不同队列的操作之间添加依赖关系,同时也要避免相互依赖。
示例: 在不同队列的操作之间添加依赖(下载-解压-安装完成-通知用户)
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
NSBlockOperation *op1 = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"下载,%@",[NSThread currentThread]);
sleep(1);
}];
NSBlockOperation *op2 = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"解压,%@",[NSThread currentThread]);
sleep(1);
}];
NSBlockOperation *op3 = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"安装完成,%@",[NSThread currentThread]);
}];
NSBlockOperation *op4 = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"通知用户,%@",[NSThread currentThread]);
}];
//添加依赖关系
[op2 addDependency:op1];
[op3 addDependency:op2];
[op4 addDependency:op3];
//将操作加入队列
[queue addOperations:[NSArray arrayWithObjects:op1, op2, op3, nil] waitUntilFinished:YES];
[[NSOperationQueue mainQueue] addOperation:op4];
/*
2020-01-20 20:38:25.298532+0800 多线程[29650:6560162] 下载,{number = 8, name = (null)}
2020-01-20 20:38:26.304068+0800 多线程[29650:6560162] 解压,{number = 8, name = (null)}
2020-01-20 20:38:27.309623+0800 多线程[29650:6568260] 安装完成,{number = 9, name = (null)}
2020-01-20 20:38:27.312105+0800 多线程[29650:6556295] 通知用户,{number = 1, name = main}
*/
GitHub:https://github.com/dolphin1208/Thread
NSOperation(苹果官方文档)