iOS底层原理 - 探寻多线程本质(二)

面试题引发的思考:

Q1: 请问下面代码的打印结果是什么?

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    dispatch_async(queue, ^{
        NSLog(@"1");
        [self performSelector:@selector(test) withObject:nil afterDelay:0];
        NSLog(@"3");
    });
}
- (void)test {
    NSLog(@"2");
}

// 打印结果
Demo[1234:567890] 1
Demo[1234:567890] 3
  • performSelector:withObject:afterDelay:的本质是往RunLoop中添加定时器;
  • 子线程默认没有启动RunLoop;
  • 所以该方法无法起到作用。

Q2: 请问下面代码的打印结果是什么?

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    NSThread *thread = [[NSThread alloc] initWithBlock:^{
        NSLog(@"1");
    }];
    [thread start];

    [self performSelector:@selector(test) onThread:thread withObject:nil waitUntilDone:YES];
}
- (void)test {
    NSLog(@"2");
}
打印结果
  • 在子线程thread中执行完NSLog(@"1");语句后,子线程thread就销毁了;
  • 然后执行test方法时,会崩溃。

Q3: 如何用GCD实现以下功能?

  • 异步并发执行任务1、任务2
  • 等任务1、任务2都执行完毕后,再回到主线程执行任务3
- (void)viewDidLoad {
    [super viewDidLoad];

    // 创建队列组
    dispatch_group_t group = dispatch_group_create();
    // 创建并发队列
    dispatch_queue_t queue = dispatch_queue_create("myqueue", DISPATCH_QUEUE_CONCURRENT);

    // 添加异步任务
    dispatch_group_async(group, queue, ^{
        for (int i=0; i<3; i++) {
            NSLog(@"任务1-%@", [NSThread currentThread]);
        }
    });
    dispatch_group_async(group, queue, ^{
        for (int i=0; i<3; i++) {
            NSLog(@"任务2-%@", [NSThread currentThread]);
        }
    });

    // 等前面的任务执行完毕后,会自动执行这个任务
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        for (int i=0; i<3; i++) {
            NSLog(@"任务3-%@", [NSThread currentThread]);
        }
    });
}
打印结果

1. 面试题Q1详解

(1) 主线程下相关问题分析

1> performSelector:withObject:方法
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    NSLog(@"1");
    [self performSelector:@selector(test) withObject:nil];
    NSLog(@"3");
}
- (void)test {
    NSLog(@"2");
}

// 打印结果
Demo[1234:567890] 1
Demo[1234:567890] 2
Demo[1234:567890] 3

Q: 为什么会出现这样的打印结果呢?

OC源码可以找到performSelector:withObject:方法实现:

performSelector:withObject:方法

由以上源码可知:

performSelector:withObject:其底层实现为:objc_msgSend(self, sel, obj)

[self performSelector:@selector(test) withObject:nil];语句等价于[self test];语句;
所以打印顺序为:1、2、3。

2> performSelector:withObject:afterDelay:方法
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    NSLog(@"1");
    [self performSelector:@selector(test) withObject:nil afterDelay:0];
    NSLog(@"3");
}
- (void)test {
    NSLog(@"2");
}

// 打印结果
Demo[1234:567890] 1
Demo[1234:567890] 3
Demo[1234:567890] 2
3> Q: 为什么打印结果和上面的不一样呢?

我们找到performSelector:withObject:afterDelay:方法实现:

performSelector:withObject:afterDelay:方法

由以上源码可知:

  • performSelector:withObject:afterDelay:方法是定义在RunLoop类中的;
  • 本质是往RunLoop中添加定时器

因为主线程的RunLoop自动创建,RunLoop在被唤醒的时候处理定时器,所以在主线程中先打印1、3,然后打印2。


(2) 子线程下相关问题分析

1> 子线程下的performSelector:withObject:方法
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    dispatch_async(queue, ^{
        NSLog(@"1");
        [self performSelector:@selector(test) withObject:nil];
        NSLog(@"3");
    });
}
- (void)test {
    NSLog(@"2");
}

// 打印结果
Demo[1234:567890] 1
Demo[1234:567890] 2
Demo[1234:567890] 3

打印结果没有什么问题,打印顺序为1、2、3。

2> 子线程下的performSelector:withObject:afterDelay:方法
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    dispatch_async(queue, ^{
        NSLog(@"1");
        // 这句代码的本质是往NSRunLoop中添加了定时器
        [self performSelector:@selector(test) withObject:nil afterDelay:0];
        NSLog(@"3");
    });
}
- (void)test {
    NSLog(@"2");
}

// 打印结果
Demo[1234:567890] 1
Demo[1234:567890] 3

Q: 为什么会出现这样的打印结果呢?

[self performSelector:@selector(test) withObject:nil afterDelay:0];这句代码的本质是往NSRunLoop中添加了定时器;
子线程默认情况下没有RunLoop,需要手动创建;所以无法起到作用。

3> 启动RunLoop
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    dispatch_async(queue, ^{
        NSLog(@"1");
        // 子线程默认没有RunLoop
        [self performSelector:@selector(test) withObject:nil afterDelay:0];
        NSLog(@"3");

        // 启动RunLoop
        [[NSRunLoop currentRunLoop] addPort:[[NSPort alloc] init] forMode:NSDefaultRunLoopMode];
        [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
    });
}
- (void)test {
    NSLog(@"2");
}

// 打印结果
Demo[1234:567890] 1
Demo[1234:567890] 3
Demo[1234:567890] 2

添加启动RunLoop代码,即可正常打印结果。

4> 分析以下代码
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    dispatch_async(queue, ^{
        [NSTimer scheduledTimerWithTimeInterval:3.0 repeats:NO block:^(NSTimer * _Nonnull timer) {
            NSLog(@"123");
        }];
    });
}

因为在子线程使用NSTimer,子线程调用方法后便会销毁,此时定时器也销毁;
3秒后便无法执行计时器内部代码,所以无法打印。


2. 面试题Q2详解

(1) NSThread相关问题

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    NSThread *thread = [[NSThread alloc] initWithBlock:^{
        NSLog(@"1");
    }];
    [thread start];

    [self performSelector:@selector(test) onThread:thread withObject:nil waitUntilDone:YES];
}
- (void)test {
    NSLog(@"2");
}
打印结果

由打印结果可知:
打印1以后崩溃,崩溃原因是等待执行perform时目标线程已退出。

原因如下:
在子线程thread中需要执行完NSLog(@"1");语句才能执行test方法;
但是执行完NSLog(@"1");语句后,子线程thread就销毁了;
所以接着执行test方法时,会崩溃。

(2) 启动RunLoop

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    NSThread *thread = [[NSThread alloc] initWithBlock:^{
        NSLog(@"1");

        // 启动RunLoop
        [[NSRunLoop currentRunLoop] addPort:[[NSPort alloc] init] forMode:NSDefaultRunLoopMode];
        [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
    }];
    [thread start];

    [self performSelector:@selector(test) onThread:thread withObject:nil waitUntilDone:YES];
}
- (void)test {
    NSLog(@"2");
}

// 打印结果
Demo[1234:567890] 1
Demo[1234:567890] 2

子线程thread内部启动了RunLoop,执行完NSLog(@"1");语句后会休眠;
[self performSelector:@selector(test) onThread:thread withObject:nil waitUntilDone:YES];语句会唤醒子线程thread的RunLoop,然后去执行test方法。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。