GCD的死锁

来源:互联网 发布:追词 知乎 编辑:程序博客网 时间:2024/05/10 17:25

GCD为多线程中的重点, 今天写了几个小demo分享一下 -J-

  • 给主线程添加同步任务
- (void)demo1{    NSLog(@"哈哈哈");    // 此处给主线程添加同步任务    // 它会等主线程任务(demo1)执行完再执行    // 而同步任务按顺序执行,也就是说同步任务不执行demo1就无法结束    // 相互等待, 形成死锁    dispatch_sync(dispatch_get_main_queue(), ^{        NSLog(@"给主队列添加同步任务");    });    NSLog(@"come here");}
  • 主队列添加异步任务
 - (void)demo2{    dispatch_async(dispatch_get_main_queue(), ^{        NSLog(@"主队列异步 %@",[NSThread currentThread]);    });    [NSThread sleepForTimeInterval:1];    NSLog(@"come here");}

执行结果: come here打印后, 主队列异步

  • 自定义串行队列同步任务
// 首先创建一个串行队列_queue = dispatch_queue_create("com.ejParadise.queue", DISPATCH_QUEUE_SERIAL);
- (void)demo3{    dispatch_sync(_queue, ^{        NSLog(@"before, %@", [NSThread currentThread]);        // 在串行队列中加入串行任务, 还是相互等待,形成死锁        dispatch_sync(_queue, ^{            NSLog(@"添加新的任务%@", [NSThread currentThread]);        });        NSLog(@"任务完毕");    });    [NSThread sleepForTimeInterval:2];    NSLog(@"会来到这儿么%@", [NSThread currentThread]);}
  • 全局并发队列异步
- (void)demo4{    dispatch_async(dispatch_get_global_queue(0, 0), ^{        NSLog(@"before%@", [NSThread currentThread]);        dispatch_sync(_queue, ^{            [NSThread sleepForTimeInterval:2];            NSLog(@"同步任务%@", [NSThread currentThread]);        });        NSLog(@"最后一个任务%@", [NSThread currentThread]);    });    [NSThread sleepForTimeInterval:2];    NSLog(@"come here%@", [NSThread currentThread]);}

打印结果:

这里写图片描述

注: 最后一个任务必定在同步任务的后面

    -
- (void)demo5{    for (int i = 0; i<100; i++) {        dispatch_async(dispatch_get_global_queue(0, 0), ^{            NSLog(@"before%d-----%@", i, [NSThread currentThread]);            dispatch_sync(_queue, ^{                NSLog(@"同步任务%d-----%@", i, [NSThread currentThread]);            });            NSLog(@"最后一个任务%d-----%@", i,[NSThread currentThread]);        });        NSLog(@"come here%d-----%@", i,[NSThread currentThread]);    }}

打印结果:

这里写图片描述

注: 最后一个任务必定排列在同步任务后面

0 0