欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

iOS - 多线程(四):NSOperation

程序员文章站 2024-03-24 13:16:58
...

iOS - 多线程 系列文章

iOS - 多线程(一):初识
iOS - 多线程(二):pthread、NSThread
iOS - 多线程(三):GCD
iOS - 多线程(四):NSOperation
iOS - 多线程(五):线程同步方案

iOS - 多线程(四):NSOperation

1. NSOperation 初识

1.1 NSOperation 介绍

  • NSOperation 是 OC 语言中基于 GCD 的面向对象的封装;
  • 提供了一些用 GCD 不好实现的功能;
  • 线程的生命周期由系统自动管理。

1.2 NSOperation 与 GCD 的区别

  • GCD
    GCD 是 iOS4.0 推出的,主要针对多核 CPU 做了优化,是 C 语言的技术;
    GCD 是将任务(block)添加到队列(串行/并发//全局/主队列),并且以同步/异步的方式执行任务的函数;
    GCD 提供了一些 NSOperation 不具备的功能:
      1. 队列组
      2. 一次性执行
      3. 延迟执行

  • NSOperation
    NSOperation 是 iOS2.0 推出的,iOS4 之后重写了 NSOperation;
    NSOperation 是将操作(异步的任务)添加到队列(并发队列),就会执行指定操作的函数;
    NSOperation 里提供的方便的操作:
      1. 最大并发数
      2. 队列的暂停/继续/取消操作
      3. 指定操作之间的依赖关系(GCD 中可以使用同步实现)

1.3 NSOperation 与 NSOperationQueue

NSOperation 需要和 NSOperationQueue 配合使用来实现多线程方案。单独使用 NSOperation 的话, 它是属于同步操作, 并不具备开启新线程的能力。

  • NSOperation:操作
      NSOperation 类是一个抽象类,不能直接使用它来封装任务,而是使用系统定义的子类( NSInvocationOperation 或 NSBlockOperation)或者自定义子类来封装任务。
      操作对象是一个单发对象,即它只执行一次任务,不能再次执行。通常通过将操作添加到操作队列来执行操作。

  • NSOperationQueue:队列
    获取主队列:[NSOperationQueue mainQueue]
    获取当前队列:[NSOperationQueue currentQueue]

1.4 NSOperation 的使用步骤

NSOperation 和 NSOperationQueue 实现多线程的步骤:

  • 创建操作: 先将需要执行的操作封装到一个 NSOperation 对象中;
  • 创建队列: 创建一个 NSOperationQueue 对象;
  • 添加操作到队列中: 然后将 NSOperation 对象添加到 NSOperationQueue 队列中。系统会自动将 NSOperationQueue 中的 NSOperation 取出来,将取出的 NSOperation 封装的操作放到一条新线程上执行。

往队列中添加操作:

- (void)addOperation:(NSOperation *)op;
- (void)addOperations:(NSArray<NSOperation *> *)ops waitUntilFinished:(BOOL)wait;
- (void)addOperationWithBlock:(void (^)(void))block

iOS - 多线程(四):NSOperation

  如果不想使用 NSOperationQueue,可以通过调用 NSOperation 对象的start方法来自己执行操作。默认情况下,调用 NSOperation 的 start 方法并不会开一条新线程去执行操作,而是在当前线程同步执行操作。

2. NSOperation 使用

2.1 NSInvocationOperation

默认情况下,调用 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] <NSThread: 0x600001482240>{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] <NSThread: 0x600001419100>{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] <NSThread: 0x600003ee8140>{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) 
 */

2.2 NSBlockOperation

三种方法

// 方法一:调用start,不会开启新线程,在当前线程同步执行
- (void)demo1 {
    NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
        NSLog(@"%@",[NSThread currentThread]);
    }];
    [operation start];
}
//2020-01-20 09:55:12.698046+0800 多线程[28530:6301526] <NSThread: 0x6000009ce200>{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] <NSThread: 0x6000009a7d00>{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] <NSThread: 0x6000009a7d00>{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] <NSThread: 0x60000108f000>{number = 3, name = (null)}
2020-01-20 10:16:08.266960+0800 多线程[28609:6321076] <NSThread: 0x6000010480c0>{number = 8, name = (null)}
2020-01-20 10:16:08.267151+0800 多线程[28609:6321077] <NSThread: 0x600001048240>{number = 9, name = (null)}
2020-01-20 10:16:08.268080+0800 多线程[28609:6320429] <NSThread: 0x60000108f000>{number = 3, name = (null)}
2020-01-20 10:16:08.267340+0800 多线程[28609:6321078] <NSThread: 0x600001048540>{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] <NSThread: 0x600003f27340>{number = 5, name = (null)}
2020-02-03 16:12:15.262491+0800 多线程[11894:2041394] 执行任务1,<NSThread: 0x600003f25e80>{number = 3, name = (null)}
2020-02-03 16:12:15.262575+0800 多线程[11894:2041399] 执行任务2,<NSThread: 0x600003fd8840>{number = 8, name = (null)}
2020-02-03 16:12:15.262653+0800 多线程[11894:2041471] 执行任务3,<NSThread: 0x600003ff1a40>{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,<NSThread: 0x600001045040>{number = 11, name = (null)}
2020-01-20 10:16:42.333687+0800 多线程[28609:6321079] end,<NSThread: 0x600001045040>{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] 下载图片,<NSThread: 0x6000037dd480>{number = 5, name = (null)}
2020-01-20 10:32:55.808920+0800 多线程[28682:6334435] 下载完成更新UI,<NSThread: 0x6000037a6680>{number = 1, name = main}
 */

3. NSOperation 进阶

3.1 最大并发数

  • 什么是并发数?
    并发数就是同时执行的任务数。
    比如,同时开3个线程执行3个任务,并发数就是3。
    但是,并发数是3,并不代表开启的线程数就是3,也有可能是4个或者5个。因为线程有可能在等待,进入了就绪状态。
  • 最大并发数属性:
@property NSInteger maxConcurrentOperationCount;
  • 执行的过程:
    1、把操作添加到队列;
    2、去线程池去取空闲的线程,如果没有就创建线程;
    3、把操作交给线程池中取出的线程执行;
    4、执行完成后,把线程再放回线程池中;
    5、重复2,3,4直到所有的操作都执行完。
  • NSOperation 与 GCD 区别:
    GCD 会自动重用线程,而 NSOperation 不会,会一直开线程。
    而开太多线程反而会影响效率,我们需要自己控制,一般开 3-6 个。
    通过最大并发数控制:
    // 控制最大并发数为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] <NSThread: 0x6000028e9340>{number = 9, name = (null)}
2020-01-20 11:04:07.401415+0800 多线程[28747:6359523] <NSThread: 0x6000028ee040>{number = 8, name = (null)}
2020-01-20 11:04:08.407240+0800 多线程[28747:6348709] <NSThread: 0x600002814bc0>{number = 6, name = (null)}
2020-01-20 11:04:08.407238+0800 多线程[28747:6359523] <NSThread: 0x6000028ee040>{number = 8, name = (null)}
2020-01-20 11:04:09.411438+0800 多线程[28747:6359523] <NSThread: 0x6000028ee040>{number = 8, name = (null)}
2020-01-20 11:04:09.411820+0800 多线程[28747:6359537] <NSThread: 0x6000028ee400>{number = 10, name = (null)}
 */

3.2 队列的暂停/继续/取消操作

/*
 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,<NSThread: 0x60000161cb80>{number = 8, name = (null)}
2020-01-20 19:40:38.138239+0800 多线程[29051:6520475] 操作1,<NSThread: 0x600001607440>{number = 9, name = (null)}
2020-01-20 19:40:39.142707+0800 多线程[29051:6389765] 操作2,<NSThread: 0x60000161cb80>{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,<NSThread: 0x600001607440>{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,<NSThread: 0x600001607440>{number = 9, name = (null)}
2020-01-20 19:40:47.184917+0800 多线程[29051:6520585] 操作5,<NSThread: 0x6000016009c0>{number = 10, name = (null)}
2020-01-20 19:40:48.189422+0800 多线程[29051:6520585] 操作6,<NSThread: 0x6000016009c0>{number = 10, name = (null)}
2020-01-20 19:40:49.192921+0800 多线程[29051:6520475] 操作7,<NSThread: 0x600001607440>{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,<NSThread: 0x6000016009c0>{number = 10, name = (null)}
 */

3.3 操作执行状态控制

操作的执行状态:

@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

3.4 操作优先级与服务质量

可以通过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,<NSThread: 0x6000010ef100>{number = 3, name = (null)}
2020-01-20 20:01:03.452049+0800 多线程[29529:6539534] 执行任务3,<NSThread: 0x6000010391c0>{number = 8, name = (null)}
2020-01-20 20:01:03.452057+0800 多线程[29529:6539535] 执行任务1,<NSThread: 0x6000010c8f00>{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,<NSThread: 0x600002327940>{number = 6, name = (null)}
2020-01-20 20:01:44.482387+0800 多线程[29558:6540420] 执行任务3,<NSThread: 0x6000023dcb00>{number = 7, name = (null)}
2020-01-20 20:01:44.482371+0800 多线程[29558:6540425] 执行任务1,<NSThread: 0x600002308d80>{number = 3, name = (null)}
 */

3.5 操作间依赖

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,<NSThread: 0x600000331240>{number = 3, name = (null)}
2020-01-20 20:26:01.718132+0800 多线程[29650:6556372] 执行任务A,<NSThread: 0x600000331240>{number = 3, name = (null)}
2020-01-20 20:26:01.721032+0800 多线程[29650:6560162] 执行任务B,<NSThread: 0x6000003ed680>{number = 8, name = (null)}
 */

可以在不同队列的操作之间添加依赖关系,同时也要避免相互依赖。
iOS - 多线程(四):NSOperation

示例: 在不同队列的操作之间添加依赖(下载-解压-安装完成-通知用户)

    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] 下载,<NSThread: 0x6000003ed680>{number = 8, name = (null)}
2020-01-20 20:38:26.304068+0800 多线程[29650:6560162] 解压,<NSThread: 0x6000003ed680>{number = 8, name = (null)}
2020-01-20 20:38:27.309623+0800 多线程[29650:6568260] 安装完成,<NSThread: 0x6000003e5180>{number = 9, name = (null)}
2020-01-20 20:38:27.312105+0800 多线程[29650:6556295] 通知用户,<NSThread: 0x600000362140>{number = 1, name = main}
 */

相关链接

GitHub:https://github.com/dolphin1208/Thread

参考

NSOperation(苹果官方文档)

相关标签: 多线程