iOS gcd - 为什么不死锁?

时间:2016-03-11 02:33:54

标签: ios grand-central-dispatch

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSLog(@"begin async:%@", [NSThread currentThread]);
        dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSLog(@"in sync:%@", [NSThread currentThread]);
        });
        NSLog(@"end async:%@", [NSThread currentThread]);
    });
    NSLog(@"end main");
}

为什么我会得到如下结果?

  1. end main
  2. 开始异步:{number = 2,name =(null)}
  3. 同步:{number = 2,name =(null)}
  4. 结束异步:{number = 2,name =(null)}
  5. 正如苹果开发者文件所说:

      

    将一个块提交到调度队列以进行同步执行。与dispatch_async不同,此函数在块完成之前不会返回。调用此函数并以当前队列为目标会导致死锁。

    "同步"和#34;结束异步"永远不会退出,这是正确的吗?

1 个答案:

答案 0 :(得分:0)

但试试这个,如果你想看到死锁:

@interface ViewController ()
@property dispatch_queue_t q;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.q = dispatch_queue_create("myq", nil);
    dispatch_sync(self.q, ^{
        NSLog(@"begin sync1:%@", [NSThread currentThread]);
        dispatch_sync(self.q, ^{
            NSLog(@"in sync2:%@", [NSThread currentThread]);
        });
        NSLog(@"end sync1:%@", [NSThread currentThread]);
    });
    NSLog(@"end main");

}

@end