美文网首页
工作总结之多线程

工作总结之多线程

作者: fleshMe | 来源:发表于2017-08-23 16:54 被阅读0次

    一、一些基本概念

    1、线程状态

    线程状态

    注:线程的死亡状态代表线程任务执行完毕,正常退出。或者手动调用[NSThread exit]手动退出。

    2、线程同步和异步

    二者的根本区别在于有没有开辟新线程的能力,同步会阻塞当前线程,异步不会阻塞当前线程。但是使用异步不一定开辟了新的线程,如下表:

    区别 并发队列 串行队列 主队列
    同步 没有开启新线程,串行执行任务 没有开启新线程,串行执行任务 主线程调用:死锁卡住不执行。其他线程调用:没有开启新线程,串行执行任务
    异步 有开启新线程,并发执行任务 有开启新线程(1条),串行执行任务 没有开启新线程,串行执行任务

    3、并行和串行

    并行是指队列中的任务执行顺序不固定,单核CPU下,通过调度算法分片执行,多核CPU下,任务可以同时执行。

    串行是指队列中的任务按照添加顺序执行

    4、线程安全

    多个线程操作同一块资源的时候,为了避免数据发生混乱,需要注意线程安全。可以通过加锁解决:

    • @synchronized(){},互斥锁。
    • NSLock
    • NSConditionLock 条件锁 可以设置条件
    #import "NSLockTest.h"
    @interface NSLockTest()
    @property (nonatomic,strong) NSMutableArray *tickets;
    @property (nonatomic,assign) int soldCount;
    @property (nonatomic,strong) NSConditionLock *condition;
    @end
    @implementation NSLockTest
    - (void)forTest
    {
        self.tickets = [NSMutableArray arrayWithCapacity:1];
        self.condition = [[NSConditionLock alloc]initWithCondition:0];
        NSThread *windowOne = [[NSThread alloc]initWithTarget:self selector:@selector(soldTicketOne) object:nil];
        [windowOne start];
        
        NSThread *windowTwo = [[NSThread alloc]initWithTarget:self selector:@selector(soldTicketTwo) object:nil];
        [windowTwo start];
       
        NSThread *windowTuiPiao = [[NSThread alloc]initWithTarget:self selector:@selector(tuiPiao) object:nil];
        [windowTuiPiao start];
    
    }
    //一号窗口
    -(void)soldTicketOne
    {
        while (YES) {
            NSLog(@"====一号窗口没票了,等别人退票");
            [self.condition lockWhenCondition:1];
            NSLog(@"====在一号窗口买了一张票,%@",[self.tickets objectAtIndex:0]);
            [self.tickets removeObjectAtIndex:0];
            [self.condition unlockWithCondition:0];
        }
    }
    //二号窗口
    -(void)soldTicketTwo
    {
        while (YES) {
            NSLog(@"====二号窗口没票了,等别人退票");
            [self.condition lockWhenCondition:2];
            NSLog(@"====在二号窗口买了一张票,%@",[self.tickets objectAtIndex:0]);
            [self.tickets removeObjectAtIndex:0];
            [self.condition unlockWithCondition:0];
        }
    }
    - (void)tuiPiao
    {
        while (YES) {
            sleep(3);
            [self.condition lockWhenCondition:0];
            [self.tickets addObject:@"南京-北京(退票)"];
            int x = arc4random() % 2;
            if (x == 1) {
                NSLog(@"====有人退票了,赶快去一号窗口买");
                [self.condition unlockWithCondition:1];
            }else
            {
                NSLog(@"====有人退票了,赶快去二号窗口买");
                [self.condition unlockWithCondition:2];
            }
        }
        
    }
    @end
    
    • NSRecursiveLock 递归锁
    //普通线程锁,会造成死锁
        NSLock *lock = [[NSLock alloc] init];
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            static void (^block)(int);
            block = ^(int value) {
                //加锁
                [lock lock];
                if (value > 0) {
                    NSLog(@"%d",value);
                    sleep(2);
                    //递归调用
                    block(--value);
                }
                //解锁
                [lock unlock];
            };
            //调用代码块
            block(10);
        });
    
    //递归锁,不会造成死锁
        NSRecursiveLock *lock = [[NSRecursiveLock alloc] init];
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            static void (^block)(int);
            block = ^(int value) {
                //加锁
                [lock lock];
                if (value > 0) {
                    NSLog(@"%d",value);
                    sleep(2);
                    //递归调用
                    block(--value);
                }
                //解锁
                [lock unlock];
            };
            //调用代码块
            block(10);
        });
    
    • dispatch_semaphore:性能第二好
    • pthread_mutex:互斥锁,性能最好
    pthread_mutex_t _lock;
    - (NSDictionary *)framePropertiesAtIndex:(NSUInteger)index {
        NSDictionary *result = nil;
        pthread_mutex_lock(&_lock);
        result = [self _framePropertiesAtIndex:index];
        pthread_mutex_unlock(&_lock);
        return result;
    }
    

    5、线程通讯

    两种情况:

    • 子线程切换到主线程
    dispatch_async(dispatch_get_main_queue(), ^{ 
      // 回到主线程,执行UI刷新操作 
    }
    
    [self performSelectorOnMainThread:@selector(displayImage:) withObject:image waitUntilDone:YES];
    [self performSelector:@selector(displayImage:) onThread:[NSThread mainThread] withObject:image waitUntilDone:YES];
    
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            // 回到主线程,执行UI刷新操作 
    }];
    
    • 主线程切换到子线程

    6、线程和进程的关系

    二、performSelector方法集

    1、

    这三个方法,均为同步执行,与线程无关,主线程和子线程中均可调用成功。等同于直接调用该方法。在需要动态的去调用方法的时候去使用。
    例如:[self performSelector:@selector(test2)];与[self test2];执行效果上完全相同。

    - (id)performSelector:(SEL)aSelector;
    - (id)performSelector:(SEL)aSelector withObject:(id)object;
    - (id)performSelector:(SEL)aSelector withObject:(id)object1 withObject:(id)object2;
    

    2、

    这两个方法为异步执行,即使delay传参为0,仍为异步执行。只能在主线程中执行,在子线程中不会调到aSelector方法。可用于当点击UI中一个按钮会触发一个消耗系统性能的事件,在事件执行期间按钮会一直处于高亮状态,此时可以调用该方法去异步的处理该事件,就能避免上面的问题。

    - (void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay inModes:(NSArray *)modes;
    - (void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay;
    

    在方法未到执行时间之前,取消方法为:

    + (void)cancelPreviousPerformRequestsWithTarget:(id)aTarget selector:(SEL)aSelector object:(id)anArgument;
    + (void)cancelPreviousPerformRequestsWithTarget:(id)aTarget;
    

    注意:调用该方法之前或在该方法所在的viewController生命周期结束的时候去调用取消函数,以确保不会引起内存泄露。

    3、

    这两个方法,在主线程和子线程中均可执行,均会调用主线程的aSelector方法;
    如果设置wait为YES:等待当前线程执行完以后,主线程才会执行aSelector方法;
    设置为NO:不等待当前线程执行完,就在主线程上执行aSelector方法。
    如果,当前线程就是主线程,那么aSelector方法会马上执行。
    注意:apple不允许程序员在主线程以外的线程中对ui进行操作,此时我们必须调用performSelectorOnMainThread函数在主线程中完成UI的更新。

    - (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait modes:(NSArray *)array;
    - (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait;
    

    4、

    调用指定线程中的某个方法。分析效果同3。

    - (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(id)arg waitUntilDone:(BOOL)wait modes:(NSArray *)array;
    - (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(id)arg waitUntilDone:(BOOL)wait;
    

    5、

    开启子线程在后台运行

    - (void)performSelectorInBackground:(SEL)aSelector withObject:(id)arg
    

    三、NSThread

    1、创建NSThread线程的方法

    • 第一种方法:
        NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(task) object:nil];
        [thread setName:@"创建线程,需要调用 start 方法"];
        [thread start];
    
    • 第二种方法:
    [NSThread detachNewThreadSelector:@selector(task) toTarget:self withObject:nil];
    
    • 第三种方法:
    [self performSelectorInBackground:@selector(task) withObject:nil];
    
    • 第四种方法:

    创建线程对象

    // 开了子线程,但是没有任务,需要告诉它任务是什么
    // 自定义类,继承NSThread
    // 重写main方法,在main方法里面封装任务
    NSThread *thread = [[CustomThread alloc] init];
    [thread setName:@"创建自定义线程,需要调用 start 方法"];
    [thread start];
    

    总结:如果你想拿到线程对象,使用第一种或者第四种方法,但是需要手动调用start。如果想创建自启线程,使用第二种或者第三种方法,但是拿不到线程对象。

    2、踩坑1

    • [thread cancel]和[NSThread exit];
      • 调用实例对象的- (void)cancel;方法、并不会直接取消线程。其作用只是对应线程的cancel属性设置为YES、线程依旧继续执行。在此之后:
        • thread.cancel为YES。
        • thread.executing为YES。
        • thread.finished为NO。(除非全执行完了)
      • 我们需要在适当的位置执行[NSThread exit];才可以真正关闭线程、余下的代码不会继续执行。同时:
        • thread.cancel为你设置的状态(默认应该是NO)。
        • thread.executing为NO。
        • thread.finished为YES。

    3、最大并发数

    - (void)concurrentNumber {
        for (int a = 0; a < 1000; a ++) {
            [self performSelectorInBackground:@selector(cn:) withObject:[NSNumber numberWithInt:a]];
        }
    }
    
    - (void)cn:(NSNumber *)number {
        NSLog(@"%@%@", number, [NSThread currentThread]);
    }
    

    log结果在1-1001不等,可以确定的是使用NSThread不支持限制最大并发数,但是如果超过某个阈值会error[NSThread start]: Thread creation failed with error 35)

    4、Example

    #import "NSThreadViewController.h"
    
    @interface NSThreadViewController ()
    
    @property (nonatomic, strong) UIImageView *imageView;
    
    @property (nonatomic, assign) NSInteger ticketCount;
    
    @end
    
    @implementation NSThreadViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        // Do any additional setup after loading the view.
        self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 100, 300, 200)];
        [self.view addSubview:self.imageView];
        [self test_six];
    }
    
    // 显式创建线程,此方法需要调用 start 方法启动线程,需要管理生命周期
    - (void)test_one {
        NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(task) object:nil];
        [thread setName:@"创建线程,需要调用 start 方法"];
        [thread start];
    }
    
    - (void)test_two {
        [NSThread detachNewThreadSelector:@selector(task) toTarget:self withObject:nil];
    }
    
    - (void)test_three {
        [self performSelectorInBackground:@selector(task) withObject:nil];
    }
    
    // 线程阻塞
    - (void)test_four {
        NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(task_preventThread) object:nil];
        [thread start];
    }
    
    - (void)task {
        [NSThread sleepForTimeInterval:2];
        NSLog(@"%@", [NSThread currentThread]);
    }
    
    - (void)task_preventThread {
        [NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:2]];
        NSLog(@"%@", [NSThread currentThread]);
        NSLog(@"%d", [NSThread isMainThread]);
        NSLog(@"%@", [NSThread mainThread]);
    }
    
    // 下载图片
    
    - (void)test_five {
        [NSThread detachNewThreadSelector:@selector(downloadImage:) toTarget:self withObject:@"https://ysc-demo-1254961422.file.myqcloud.com/YSC-phread-NSThread-demo-icon.jpg"];
    }
    
    - (void)downloadImage:(NSString *)urlString {
        NSURL *url = [NSURL URLWithString:urlString];
        NSData *data = [NSData dataWithContentsOfURL:url];
        UIImage *image = [UIImage imageWithData:data];
        [self performSelectorOnMainThread:@selector(displayImage:) withObject:image waitUntilDone:YES];
    }
    
    - (void)displayImage:(UIImage *)image {
        self.imageView.image = image;
    }
    
    // 线程同步
    - (void)test_six {
        self.ticketCount = 50;
        NSThread *thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(sellTicket) object:nil];
        thread1.name = @"线程1";
        [thread1 start];
        
        NSThread *thread2 = [[NSThread alloc] initWithTarget:self selector:@selector(sellTicket) object:nil];
        thread2.name = @"线程2";
        [thread2 start];
    }
    
    - (void)sellTicket {
        while (1) {
            @synchronized (self) {
                if (self.ticketCount > 0) {
                    self.ticketCount --;
                    NSLog(@"当前线程:%@,剩余票数:%ld", [NSThread currentThread].name, self.ticketCount);
                } else {
                    NSLog(@"所有的票已经卖完");
                    break;
                }
            }
        }
    }
    
    @end
    

    四、NSOperation

    1、自定义非并发 NSOperation

    • 要点:重写 main 函数,创建自动释放池,如果操作未取消,就执行操作
    #import <Foundation/Foundation.h>
    
    @interface ZYOperation : NSOperation
    
    @end
    
    
    #import "ZYOperation.h"
    
    @implementation ZYOperation
    
    - (void)main {
        // 这里获取不到主线程的自动释放池,所以创建自动释放池自动释放内部创建的对象
        @autoreleasepool {
            if (!self.isCancelled) {
                // 这里写上任务代码
                NSLog(@"%@", [NSThread currentThread]);
            }
        }
    }
    
    @end
    

    2、自定义并发 NSOperation

    • 要点:
      • 定义 finishen、executing 实例变量,在 init 方法中初始化其值,并重写 isConcurrent(必须重写)、isFinished、isExecuting、start、main 方法。
      • 在 start 方法中任务判断是否被取消,如果已取消,手动出发 isFinished 的KVO,否则手动出发 Executing 的KVO,并使用 NSThread 后台执行 main 函数。
    #import <Foundation/Foundation.h>
    
    @interface ZYConcurrentOperation : NSOperation {
        BOOL executing;
        BOOL finished;
    }
    
    @end
    
    
    #import "ZYConcurrentOperation.h"
    
    @implementation ZYConcurrentOperation
    
    - (instancetype)init {
        self = [super init];
        if (self) {
            finished = NO;
            executing = NO;
        }
        return self;
    }
    
    - (BOOL)isFinished {
        return finished;
    }
    
    - (BOOL)isExecuting {
        return executing;
    }
    
    - (BOOL)isConcurrent {
        return YES;
    }
    
    - (void)start {
        if (self.isCancelled) {
            [self willChangeValueForKey:@"isFinished"];
            finished = YES;
            [self didChangeValueForKey:@"isFinished"];
            return;
        }
        
        [self willChangeValueForKey:@"isExecuting"];
        executing = YES;
        [NSThread detachNewThreadSelector:@selector(main) toTarget:self withObject:nil];
        [self didChangeValueForKey:@"isExecuting"];
    }
    
    - (void)main {
        @autoreleasepool {
            // 这里执行自定义任务
            NSLog(@"%@", [NSThread currentThread]);
            
            [self willChangeValueForKey:@"isExecuting"];
            [self willChangeValueForKey:@"isFinished"];
            finished = NO;
            executing = YES;
            [self didChangeValueForKey:@"isExecuting"];
            [self didChangeValueForKey:@"isFinished"];
        }
    }
    
    @end
    

    3、创建的Operation是不是多线程执行的实验:

        // 多线程
        NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(task) object:nil];
        NSOperationQueue *queue = [[NSOperationQueue alloc] init];
        [queue addOperation:operation];
        // 这里 block 会被回调
        [operation setCompletionBlock:^{
            NSLog(@"操作执行完成");
        }];
    
    
        // 多线程
        NSInvocationOperation *operation1 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(task_1) object:nil];
        operation1.queuePriority = NSOperationQueuePriorityLow;
        NSInvocationOperation *operation2 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(task_2) object:nil];
        operation2.queuePriority = NSOperationQueuePriorityHigh;
        NSOperationQueue *queue = [[NSOperationQueue alloc] init];
        [queue addOperation:operation1];
        [queue addOperation:operation2];
    
    
        // 非多线程
        NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
            NSLog(@"%@", [NSThread currentThread]);
        }];
        [operation start];
    
    
        // 添加的操作数大于1时,可能是多线程
        NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
            NSLog(@"%@", [NSThread currentThread]);
        }];
        [operation addExecutionBlock:^{
            NSLog(@"%@", [NSThread currentThread]);
        }];
        [operation start];
    
    
        // 多线程
        NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
            NSLog(@"%@", [NSThread currentThread]);
        }];
        NSOperationQueue *queue = [[NSOperationQueue alloc] init];
        [queue addOperation:operation];
    
    

    4、依赖关系

    • 依赖必须在操作被添加到队列(确切来说应该是被执行)之前设置、否则无效
    • 这个例子说明 NSOperationQueue 不同于 GCD 中队列 FIFO 的规则,队列中的执行顺序与依赖关系和优先级有关
    • 取消依赖关系[operation1 removeDependency:operation0];
    • 操作的依赖关系与本身绑定、并不受限于同一个队列。即使所执行的队列不同、也可以完成依赖操作
        NSBlockOperation *operation0 = [NSBlockOperation blockOperationWithBlock:^{
            NSLog(@"%@,0", [NSThread currentThread]);
        }];
        NSBlockOperation *operation1 = [NSBlockOperation blockOperationWithBlock:^{
            NSLog(@"%@,1", [NSThread currentThread]);
        }];
        NSBlockOperation *operation2 = [NSBlockOperation blockOperationWithBlock:^{
            NSLog(@"%@,2", [NSThread currentThread]);
            NSLog(@"%@", NSOperationQueue.currentQueue);
        }];
        NSBlockOperation *operation3 = [NSBlockOperation blockOperationWithBlock:^{
            NSLog(@"%@,3", [NSThread currentThread]);
            NSLog(@"%@", NSOperationQueue.mainQueue);
        }];
        [operation1 addDependency:operation0];
        [operation2 addDependency:operation1];
        [operation3 addDependency:operation2];
        NSOperationQueue *queue = [NSOperationQueue new];
        [queue addOperation:operation0];
        [queue addOperation:operation1];
        [queue addOperation:operation2];
        [queue addOperation:operation3];
    

    5、依赖关系和优先级的判定

    • 先判定依赖关系,再执行优先级
    • 下面代码先执行任务3,再执行高优先级任务,最后执行低优先级任务
        NSOperationQueue *operationQueue=[[NSOperationQueue alloc]init];
        
        operationQueue.maxConcurrentOperationCount = 1;
        
        NSBlockOperation *blockOperation1=[NSBlockOperation blockOperationWithBlock:^{
            NSLog(@"低优先级任务");
        }];
        blockOperation1.queuePriority = NSOperationQueuePriorityLow;
        
        NSBlockOperation *blockOperation2=[NSBlockOperation blockOperationWithBlock:^{
            NSLog(@"高优先级任务");
            sleep(1);
        }];
        blockOperation2.queuePriority = NSOperationQueuePriorityHigh;
        
        NSBlockOperation *blockOperation3 = [NSBlockOperation blockOperationWithBlock:^{
            NSLog(@"任务3");
        }];
        
        [blockOperation1 addDependency:blockOperation3];
        [blockOperation2 addDependency:blockOperation3];
        
        [operationQueue addOperation:blockOperation1];
        [operationQueue addOperation:blockOperation2];
        [operationQueue addOperation:blockOperation3];
    

    6、依赖在添加进队列之后虽然不能追加。但是可以对某操作进行追加addExecutionBlock、也可以延后操作的执行。

        NSOperationQueue *operationQueue=[[NSOperationQueue alloc]init];
        
        NSBlockOperation * blockOperation1 = [NSBlockOperation blockOperationWithBlock:^{
            NSLog(@"进入操作1");
            sleep(3);
            NSLog(@"操作1完成");
        }];
        
        NSBlockOperation * blockOperation2 = [NSBlockOperation blockOperationWithBlock:^{
            NSLog(@"进入依赖操作");
        }];
        
        [blockOperation2 addDependency:blockOperation1];
        
        [operationQueue addOperation:blockOperation1];
        [operationQueue addOperation:blockOperation2];
        
        [blockOperation1 addExecutionBlock:^{
            NSLog(@"进入追加操作");
            sleep(5);
            NSLog(@"追加操作完成");
        }];
    

    7、串行和并行的控制

    • 通过maxConcurrentOperationCount,如果设置为1,则为串行,大于1,为并行
    • maxConcurrentOperationCount值默认为-1,不指定其值得情况下,默认为并行,指定其值为0,则不会执行queue中添加的操作
        NSBlockOperation *operation0 = [NSBlockOperation blockOperationWithBlock:^{
            NSLog(@"%@,0", [NSThread currentThread]);
        }];
        NSBlockOperation *operation1 = [NSBlockOperation blockOperationWithBlock:^{
            NSLog(@"%@,1", [NSThread currentThread]);
        }];
        NSBlockOperation *operation2 = [NSBlockOperation blockOperationWithBlock:^{
            NSLog(@"%@,2", [NSThread currentThread]);
        }];
        NSBlockOperation *operation3 = [NSBlockOperation blockOperationWithBlock:^{
            NSLog(@"%@,3", [NSThread currentThread]);
        }];
        NSArray <NSOperation *>*operationArray = [NSArray arrayWithObjects:operation0, operation1, operation2, operation3, nil];
        NSOperationQueue *queue = [[NSOperationQueue alloc] init];
        queue.maxConcurrentOperationCount = 2;
        [queue addOperations:operationArray waitUntilFinished:NO];
    

    8、任务数组阻塞和单个任务阻塞

    • 单个任务阻塞
      • 阻塞当前线程、直到该操作执行完成
    NSOperationQueue *operationQueue=[[NSOperationQueue alloc]init];
        NSBlockOperation *blockOperation3=[NSBlockOperation blockOperationWithBlock:^{
            
            sleep(3);
            NSLog(@"操作3执行完毕");
        }];
        
        NSBlockOperation *blockOperation2=[NSBlockOperation blockOperationWithBlock:^{
            NSLog(@"操作2开始执行");
            [blockOperation3 waitUntilFinished];
            NSLog(@"操作2执行完毕");
        }];
        [operationQueue addOperation:blockOperation2];
        [operationQueue addOperation:blockOperation3];
    
    • 任务数组阻塞
      • 如果为YES。阻塞当前线程、直到队列该次添加的所有操作全部执行完成。
      • 如果为NO。就是批量添加操作而已
    NSOperationQueue *operationQueue=[[NSOperationQueue alloc]init];
        NSBlockOperation *blockOperation3=[NSBlockOperation blockOperationWithBlock:^{
            sleep(3);
            NSLog(@"操作3执行完毕");
        }];
        NSLog(@"添加操作");
        [operationQueue addOperations:@[blockOperation3] waitUntilFinished:YES];
        NSLog(@"添加完成");
    

    9、主队列([NSOperationQueue mainQueue])可以不可以修改最大并发数?主队列下添加的操作、都会在主线程执行么?

    • 不能、主队列的最大并发数始终为1(自定义队列默认为-1)、且修改无效。
    • 默认状况下是的、但也有例外(追加操作addExecutionBlock)。

    10、NSOperationQueue的最大并发数

    • 我测试了一下,创建100个任务时,最大值为66。

    11、NSOperation的优势

    • 可添加完成的代码块,在操作完成后执行。
    • 添加操作之间的依赖关系,方便的控制执行顺序。
    • 设定操作执行的优先级。
    • 可以很方便的取消一个操作的执行。
    • 使用 KVO 观察对操作执行状态的更改:isExecuteing、isFinished、isCancelled。

    五、GCD

    • GCD:是 Apple 开发的一个多核编程的较新的解决方法。它主要用于优化应用程序以支持多核处理器。(来自百度百科)
    • 同步和异步:二者根本的区别是有没有开辟新线程的能力,以及是否等待上一个任务执行完毕。顺序执行和并发执行。
    • 队列:队列是一种特殊的线性表,采用 FIFO(先进先出)的原则,即新任务总是被插入到队列的末尾,而读取任务的时候总是从队列的头部开始读取。每读取一个任务,则从队列中释放一个任务

    1、GCD 优势

    • GCD 可用于多核的并行运算
    • GCD 会自动利用更多的 CPU 内核(比如双核、四核)
    • GCD 会自动管理线程的生命周期(创建线程、调度任务、销毁线程)
    • 程序员只需要告诉 GCD 想要执行什么任务,不需要编写任何线程管理代码

    2、队列的创建

    // 主队列:用来执行主线程上的操作任务
    dispatch_queue_t mainQueue   = dispatch_get_main_queue();
    
    // 创建串行队列:第一个参数是队列名称,第二个参数是队列类型(串行或并行)
    dispatch_queue_t serialQueue = dispatch_queue_create(<#const char * _Nullable label#>, <#dispatch_queue_attr_t  _Nullable attr#>);
    
    // 创建并行队列的两种方式
    // 1、第一个参数是队列优先级,第二个参数是预留的,传0即可
    dispatch_queue_t concurrentQueue1 = dispatch_get_global_queue(<#long identifier#>, <#unsigned long flags#>);
    //2、第一个参数是队列名称,第二个参数是队列类型(串行或并行)
    dispatch_queue_t concurrentQueue2 = dispatch_queue_create(<#const char * _Nullable label#>, <#dispatch_queue_attr_t  _Nullable attr#>);
    

    3、GCD 的其他方法

    栅栏函数:dispatch_barrier_async

    dispatch_barrier_async函数会等待前边追加到并发队列中的任务全部执行完毕之后,再将指定的任务追加到该异步队列中。然后在dispatch_barrier_async函数追加的任务执行完毕之后,异步队列才恢复为一般动作,接着追加任务到该异步队列并开始执行。

    - (void)barrier {
        dispatch_queue_t queue = dispatch_queue_create("net.bujige.testQueue", DISPATCH_QUEUE_CONCURRENT);
        
        dispatch_async(queue, ^{
            // 追加任务1
            for (int i = 0; i < 2; ++i) {
                [NSThread sleepForTimeInterval:2];              // 模拟耗时操作
                NSLog(@"1---%@",[NSThread currentThread]);      // 打印当前线程
            }
        });
        dispatch_async(queue, ^{
            // 追加任务2
            for (int i = 0; i < 2; ++i) {
                [NSThread sleepForTimeInterval:2];              // 模拟耗时操作
                NSLog(@"2---%@",[NSThread currentThread]);      // 打印当前线程
            }
        });
        
        dispatch_barrier_async(queue, ^{
            // 追加任务 barrier
            for (int i = 0; i < 2; ++i) {
                [NSThread sleepForTimeInterval:2];              // 模拟耗时操作
                NSLog(@"barrier---%@",[NSThread currentThread]);// 打印当前线程
            }
        });
        
        dispatch_async(queue, ^{
            // 追加任务3
            for (int i = 0; i < 2; ++i) {
                [NSThread sleepForTimeInterval:2];              // 模拟耗时操作
                NSLog(@"3---%@",[NSThread currentThread]);      // 打印当前线程
            }
        });
        dispatch_async(queue, ^{
            // 追加任务4
            for (int i = 0; i < 2; ++i) {
                [NSThread sleepForTimeInterval:2];              // 模拟耗时操作
                NSLog(@"4---%@",[NSThread currentThread]);      // 打印当前线程
            }
        });
    }
    

    GCD 延时执行方法:dispatch_after

    - (void)after {
        NSLog(@"currentThread---%@",[NSThread currentThread]);  // 打印当前线程
        NSLog(@"asyncMain---begin");
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 2.0秒后异步追加任务代码到主队列,并开始执行
            NSLog(@"after---%@",[NSThread currentThread]);  // 打印当前线程
        });
    }
    // 需要注意的是,dispatch_after并不是在指定的时间之后执行处理,而是在指定的时间之后追加到dispatch queue处理。此源码的作用是,在指定的时间之后,追加到main dispatch queue处理;
    

    dispatch_once

    - (void)once {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            // 只执行1次的代码(这里面默认是线程安全的)
        });
    }
    

    dispatch_group

    • NSOperation的添加进队列后可不可以追加依赖?GCD任务组添加监听后可不可以追加任务?
      • NSOperation的依赖必须在添加进队列(并且执行前)之前设置。(但是我们可以对某被依赖的操作进行追加addExecutionBlock以延缓调用)

      • GCD任务组则具备追加任务的功能。前提是监听并未被触发。

        NSLog(@"..............start..............");
        dispatch_group_t group = dispatch_group_create();
        dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSLog(@"第一组任务");
            [NSThread sleepForTimeInterval:1];
        });
        dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSLog(@"第二组任务");
            [NSThread sleepForTimeInterval:1];
        });
        dispatch_group_notify(group, dispatch_get_main_queue(), ^{
            NSLog(@"%@", [NSThread currentThread]);
            [NSThread sleepForTimeInterval:1];
        });
        NSLog(@"...............end...............");
    }
    /*
     2019-02-23 19:48:35.942689+0800 Group[10209:459897] ..............start..............
     2019-02-23 19:48:35.942921+0800 Group[10209:459897] ...............end...............
     2019-02-23 19:48:35.943606+0800 Group[10209:459928] 第一组任务
     2019-02-23 19:48:35.943636+0800 Group[10209:459930] 第二组任务
     2019-02-23 19:48:36.947657+0800 Group[10209:459897] <NSThread: 0x600000a01340>{number = 1, name = main}
    */
    
    - (void)test_2 {
        NSLog(@"..............start..............");
        dispatch_group_t group = dispatch_group_create();
        dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSLog(@"第一组任务");
            [NSThread sleepForTimeInterval:1];
        });
        dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSLog(@"第二组任务");
            [NSThread sleepForTimeInterval:1];
        });
        dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
        NSLog(@"...............end...............");
    }
    /*
     2019-02-23 19:47:56.637099+0800 Group[10196:459432] ..............start..............
     2019-02-23 19:47:56.637425+0800 Group[10196:459471] 第一组任务
     2019-02-23 19:47:56.637485+0800 Group[10196:459472] 第二组任务
     2019-02-23 19:47:57.639444+0800 Group[10196:459432] ...............end...............
    */
    
    - (void)test_3 {
        NSLog(@"..............start..............");
        dispatch_group_t group = dispatch_group_create();
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        
        dispatch_group_enter(group);
        dispatch_async(queue, ^{
            NSLog(@"第一组任务");
            [NSThread sleepForTimeInterval:1];
            dispatch_group_leave(group);
        });
        
        dispatch_group_enter(group);
        dispatch_async(queue, ^{
            NSLog(@"第二组任务");
            [NSThread sleepForTimeInterval:1];
            dispatch_group_leave(group);
        });
        
        dispatch_group_notify(group, dispatch_get_main_queue(), ^{
            NSLog(@"%@", [NSThread currentThread]);
            [NSThread sleepForTimeInterval:1];
        });
        NSLog(@"...............end...............");
    }
    /*
     19-02-23 19:43:17.207690+0800 Group[10144:457044] ..............start..............
     2019-02-23 19:43:17.207927+0800 Group[10144:457044] ...............end...............
     2019-02-23 19:43:17.207967+0800 Group[10144:457104] 第二组任务
     2019-02-23 19:43:17.207985+0800 Group[10144:457103] 第一组任务
     2019-02-23 19:43:18.212495+0800 Group[10144:457044] <NSThread: 0x60000177a900>{number = 1, name = main}
    */
    

    GCD 信号量:dispatch_semaphore

    - (NSArray *)tasksForKeyPath:(NSString *)keyPath {
        __block NSArray *tasks = nil;
        dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
        [self.session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
            if ([keyPath isEqualToString:NSStringFromSelector(@selector(dataTasks))]) {
                tasks = dataTasks;
            } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(uploadTasks))]) {
                tasks = uploadTasks;
            } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(downloadTasks))]) {
                tasks = downloadTasks;
            } else if ([keyPath isEqualToString:NSStringFromSelector(@selector(tasks))]) {
                tasks = [@[dataTasks, uploadTasks, downloadTasks] valueForKeyPath:@"@unionOfArrays.self"];
            }
    
            dispatch_semaphore_signal(semaphore);
        }];
    
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    
        return tasks;
    }
    
    // 控制线程并发数1
    dispatch_queue_t concurrentQueue = dispatch_queue_create("concurrentQueue", DISPATCH_QUEUE_CONCURRENT);
        dispatch_queue_t serialQueue = dispatch_queue_create("serialQueue",DISPATCH_QUEUE_SERIAL);
        dispatch_semaphore_t semaphore = dispatch_semaphore_create(4);
        for (NSInteger i = 0; i < 15; i++) {
            dispatch_async(serialQueue, ^{
                dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
                dispatch_async(concurrentQueue, ^{
                    NSLog(@"thread:%@开始执行任务%d",[NSThread currentThread],(int)i);
                    sleep(1);
                    NSLog(@"thread:%@结束执行任务%d",[NSThread currentThread],(int)i);
                    dispatch_semaphore_signal(semaphore);});
            });
        }
    
    /**
     * 线程安全:使用 semaphore 加锁
     * 初始化火车票数量、卖票窗口(线程安全)、并开始卖票
     */
    - (void)initTicketStatusSave {
        NSLog(@"currentThread---%@",[NSThread currentThread]);  // 打印当前线程
        NSLog(@"semaphore---begin");
        
        semaphoreLock = dispatch_semaphore_create(1);
        
        self.ticketSurplusCount = 50;
        
        // queue1 代表北京火车票售卖窗口
        dispatch_queue_t queue1 = dispatch_queue_create("net.bujige.testQueue1", DISPATCH_QUEUE_SERIAL);
        // queue2 代表上海火车票售卖窗口
        dispatch_queue_t queue2 = dispatch_queue_create("net.bujige.testQueue2", DISPATCH_QUEUE_SERIAL);
        
        __weak typeof(self) weakSelf = self;
        dispatch_async(queue1, ^{
            [weakSelf saleTicketSafe];
        });
        
        dispatch_async(queue2, ^{
            [weakSelf saleTicketSafe];
        });
    }
    
    /**
     * 售卖火车票(线程安全)
     */
    - (void)saleTicketSafe {
        while (1) {
            // 相当于加锁
            dispatch_semaphore_wait(semaphoreLock, DISPATCH_TIME_FOREVER);
            
            if (self.ticketSurplusCount > 0) {  //如果还有票,继续售卖
                self.ticketSurplusCount--;
                NSLog(@"%@", [NSString stringWithFormat:@"剩余票数:%d 窗口:%@", self.ticketSurplusCount, [NSThread currentThread]]);
                [NSThread sleepForTimeInterval:0.2];
            } else { //如果已卖完,关闭售票窗口
                NSLog(@"所有火车票均已售完");
                
                // 相当于解锁
                dispatch_semaphore_signal(semaphoreLock);
                break;
            }
            
            // 相当于解锁
            dispatch_semaphore_signal(semaphoreLock);
        }
    }
    

    dispatch_set_target_queue

    作用:变更生成的dispatch queue的优先级

    dispatch_apply

    快速迭代遍历,多线程进行。
    下面代码end输出是在dispatch_apply完成之后。

    dispatch_queue_t queue =dispatch_queue_create("apply并行队列", DISPATCH_QUEUE_CONCURRENT);
        dispatch_apply(count, queue, ^(size_t index) {
            NSLog(@"%@----%@",array[index],[NSThread currentThread]);
        });
    NSLog(@"end");
    

    四、GCD执行任务的顺序

    场景一

    - (void)examine {
        NSLog(@"1"); // 任务1
        dispatch_sync(dispatch_get_main_queue(), ^{
            NSLog(@"2"); // 任务2
        });
        NSLog(@"3"); // 任务3
    }
    
    // log
    1
    
    /*
    *  主线程执行 examine 方法,相当于把 examine 放到了主线程的队列当中
    *  接下来遇到了同步执行,相当于把任务 2 放到了主线程的队列当中
    *  此时的情况是,任务 2 会等待 examine 执行完成,同时,由于是同步执行,examine 也会等待 任务 2 执行完成,形成死锁
    *  也可以这样说,examine 函数中的任务 3 会等待 任务 2 执行完成,任务 2 会等待 examine 中的任务 3 执行完成,形成死锁
    *  导致程序崩溃
    */
    

    场景二

    - (void)examine {
        NSLog(@"1"); // 任务1
        dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
            NSLog(@"2"); // 任务2
        });
        NSLog(@"3"); // 任务3
    }
    
    // log:
    1
    2
    3
    /*
    *  主线程执行 examine 方法,相当于把 examine 放到了主线程的队列当中
    *  接下来遇到同步任务,相当于把任务 2 放到了子队列当中执行
    *  任务 2 执行完成之后,回到主线程,继续执行任务 3
    *  不会造成死锁
    */
    

    场景三

    - (void)examine {
        dispatch_queue_t queue = dispatch_queue_create("com.demo.serialQueue", DISPATCH_QUEUE_SERIAL);
        NSLog(@"1"); // 任务1
        dispatch_async(queue, ^{
            NSLog(@"2"); // 任务2
            dispatch_sync(queue, ^{
                NSLog(@"3"); // 任务3
            });
            NSLog(@"4"); // 任务4
        });
        NSLog(@"5"); // 任务5
    }
    
    // log:
    1
    5
    2
    // 5和2顺序不一定
    
    /*
    *  执行任务 1,接下来遇到串行队列异步执行,不会阻塞线程,接下来有可能执行任务 5
    *  在异步执行的过程中,先执行任务 2,接下来遇到同步执行,并且将同步任务 3 放到当前串行队列当中
    *  所以任务 3 会等待此串行队列中的任务 4 执行完毕
    *  由于次串行队列中遇到同步任务 3,他就会等待任务 3 执行完成之后再执行任务 4,形成死锁
    *  造成程序崩溃
    */
    

    场景四

    - (void)examine {
        NSLog(@"1"); // 任务1
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            NSLog(@"2"); // 任务2
            dispatch_sync(dispatch_get_main_queue(), ^{
                NSLog(@"3"); // 任务3
            });
            NSLog(@"4"); // 任务4
        });
        NSLog(@"5"); // 任务5
    }
    
    // log:
    1
    2
    5
    3
    4
    // 5和2顺序不定
    /*
    *  首先,将【任务1、异步线程、任务5】加入Main Queue中,异步线程中的任务是:【任务2、同步线程、任务4】。
    *  所以,先执行任务1,然后将异步线程中的任务加入到Global Queue中,因为异步线程,所以任务5不用等待,结果就是2和5的输出顺序不一定。
    *  然后再看异步线程中的任务执行顺序。任务2执行完以后,遇到同步线程。将同步线程中的任务加入到Main Queue中,这时加入的任务3在任务5的后面。
    *  当任务3执行完以后,没有了阻塞,程序继续执行任务4。
    *  从以上的分析来看,得到的几个结果:1最先执行;2和5顺序不一定;4一定在3后面。
    */
    

    场景五

    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSLog(@"1"); // 任务1
        dispatch_sync(dispatch_get_main_queue(), ^{
            NSLog(@"2"); // 任务2
        });
        NSLog(@"3"); // 任务3
    });
    NSLog(@"4"); // 任务4
    while (1) {
    }
    NSLog(@"5"); // 任务5
    
    // log:
    1
    4
    // 1和4顺序不定
    /*
    *  和上面几个案例的分析类似,先来看看都有哪些任务加入了Main Queue:【异步线程、任务4、死循环、任务5】。
    *  在加入到Global Queue异步线程中的任务有:【任务1、同步线程、任务3】。
    *  第一个就是异步线程,任务4不用等待,所以结果任务1和任务4顺序不一定。
    *  任务4完成后,程序进入死循环,Main Queue阻塞。但是加入到Global Queue的异步线程不受影响,继续执行任务1后面的同步线程。
    *  同步线程中,将任务2加入到了主线程,并且,任务3等待任务2完成以后才能执行。
    *  这时的主线程,已经被死循环阻塞了。所以任务2无法执行,当然任务3也无法执行,在死循环后的任务5也不会执行。
    *  最终,只能得到1和4顺序不定的结果。
    */
    

    场景六

    - (void)examine {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"A");
        });
        NSLog(@"B");
        dispatch_queue_t queueTemp = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0ul);
        dispatch_async(queueTemp, ^{
            NSLog(@"C");
        });
        dispatch_async(queueTemp, ^{
            NSLog(@"D");
        });
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"E");
        });
        /*
         *  此方法为异步执行,即使 afterDelay 为 0,仍为异步
         *  method 方法会在主线程中执行
         *  所以,此方法相当于 主线程中的异步任务
         */
        [self performSelector:@selector(method) withObject:nil afterDelay:0.0];
        NSLog(@"F");
    }
    /*
    *  执行顺序为 B C D F A E G
    *  其中 C 和 D 的顺序不定
    *  并且 C 和 D 可能在 B 和 G 之间的任一个时刻执行
    */
    

    相关文章

      网友评论

          本文标题:工作总结之多线程

          本文链接:https://www.haomeiwen.com/subject/ntuarxtx.html