美文网首页
GCD面试题

GCD面试题

作者: Cwwng | 来源:发表于2020-11-15 13:41 被阅读0次

1、并发队列

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    dispatch_queue_t queue = dispatch_queue_create("cwwng-queue", DISPATCH_QUEUE_CONCURRENT);
    
    NSLog(@"1");
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(4.0 * NSEC_PER_SEC)), queue, ^{
        
        NSLog(@"2");
        dispatch_sync(queue, ^{
           
            NSLog(@"3");
        });
    });
    
    NSLog(@"4");
    dispatch_sync(queue, ^{
       
        NSLog(@"5");
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), queue, ^{
            
            NSLog(@"6");
        });
    });
    
    NSLog(@"7");
}
2020-11-15 12:05:55.373847+0800 Demo[17480:3389983] 1
2020-11-15 12:05:55.374025+0800 Demo[17480:3389983] 4
2020-11-15 12:05:55.374164+0800 Demo[17480:3389983] 5
2020-11-15 12:05:55.374294+0800 Demo[17480:3389983] 7
2020-11-15 12:05:56.374415+0800 Demo[17480:3390085] 6
2020-11-15 12:05:59.374256+0800 Demo[17480:3390741] 2
2020-11-15 12:05:59.374563+0800 Demo[17480:3390741] 3

2、换成串行队列程序奔溃

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    dispatch_queue_t queue = dispatch_queue_create("cwwng-queue", DISPATCH_QUEUE_SERIAL);
    
    NSLog(@"1");
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(4.0 * NSEC_PER_SEC)), queue, ^{
        
        NSLog(@"2");
        dispatch_sync(queue, ^{
           
            NSLog(@"3");
        });
    });
    
    NSLog(@"4");
    dispatch_sync(queue, ^{
       
        NSLog(@"5");
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), queue, ^{
            
            NSLog(@"6");
        });
    });
    
    NSLog(@"7");
}
2020-11-15 12:09:01.525544+0800 Demo[17654:3394594] 1
2020-11-15 12:09:01.525743+0800 Demo[17654:3394594] 4
2020-11-15 12:09:01.525858+0800 Demo[17654:3394594] 5
2020-11-15 12:09:01.525985+0800 Demo[17654:3394594] 7
2020-11-15 12:09:02.526170+0800 Demo[17654:3394947] 6
2020-11-15 12:09:05.525985+0800 Demo[17654:3394947] 2

3、对于问题2的简单表现形式,程序奔溃

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    dispatch_queue_t queue = dispatch_queue_create("cwwng-queue", DISPATCH_QUEUE_SERIAL);
    
    NSLog(@"1");
    dispatch_async(queue, ^{
       
        NSLog(@"2");
        dispatch_sync(queue, ^{
           
            NSLog(@"3");
        });
    });
    NSLog(@"4");
}
2020-11-15 13:35:27.532041+0800 Demo[21321:3470514] 1
2020-11-15 13:35:27.532238+0800 Demo[21321:3470514] 4
2020-11-15 13:35:27.533207+0800 Demo[21321:3470755] 2

相关文章

网友评论

      本文标题:GCD面试题

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