iOS gcd面试题

1.异步+并发

dispatch_queue_t queue = dispatch_queue_create("com.demo.conQueue", DISPATCH_QUEUE_CONCURRENT);
    NSLog(@"1");
    dispatch_async(queue, ^{
        // 还是会按顺序执行
        NSLog(@"%@ 2-1",[NSThread currentThread]);
        NSLog(@"%@ 2-2",[NSThread currentThread]);
        NSLog(@"%@ 2-3",[NSThread currentThread]);
    });
    dispatch_async(queue, ^{
        NSLog(@"%@ 3",[NSThread currentThread]);
    });
    dispatch_async(queue, ^{
        NSLog(@"%@ 4",[NSThread currentThread]);
    });
    NSLog(@"5");

    // 结果
    /*
     1
     5
     <NSThread: 0x60000174dfc0>{number = 3, name = (null)} 2-1
     <NSThread: 0x600001704540>{number = 6, name = (null)} 3
     <NSThread: 0x600001758f40>{number = 7, name = (null)} 4
     <NSThread: 0x60000174dfc0>{number = 3, name = (null)} 2-2
     <NSThread: 0x60000174dfc0>{number = 3, name = (null)} 2-3
     */

2.同步/异步 + 串行队列

    dispatch_queue_t queue = dispatch_queue_create("com.demo.serialQueue", DISPATCH_QUEUE_SERIAL);
    NSLog(@"1");
    
    // 异步+串行 --> 能够开辟一条新线程
    dispatch_async(queue, ^{
        NSLog(@"%@ 2",[NSThread currentThread]);
        // 死锁,同步 + 当前队列 --> 死锁
        dispatch_sync(queue, ^{
            NSLog(@"3");
        });
        NSLog(@"%@ 4",[NSThread currentThread]);
    });
    NSLog(@"5");
    
    // 结果
    /*
     1
     5
     <NSThread: 0x600001749100>{number = 6, name = (null)} 2
     死锁了
     */
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容