Objective C在不同线程中嵌套@synchronized



对于这个测试场景,我有一个问题:

- (void)testP{
dispatch_group_t group1 = dispatch_group_create();
dispatch_group_t group2 = dispatch_group_create();
NSString* test = @"1";
@synchronized (test) {
NSLog(@"%@👌", [NSThread currentThread]);
dispatch_group_async(group1, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSLog(@"%@👌", [NSThread currentThread]);
@synchronized (test) {
dispatch_group_async(group2, dispatch_queue_create("com.test.Test", NULL) , ^{
NSLog(@"%@👌", [NSThread currentThread]);
NSLog(@"👌👌👌👌");
});
}
});
}

dispatch_group_wait(group2, DISPATCH_TIME_FOREVER);
}

输出如下:

2021-03-09 16:08:52.385549-0800 xctest[43085:14812554] <NSThread: 0x7faa8d004ba0>{number = 1, name = main}👌
2021-03-09 16:08:52.385701-0800 xctest[43085:14812745] <NSThread: 0x7faa8b520770>{number = 4, name = (null)}👌
2021-03-09 16:08:52.385848-0800 xctest[43085:14812747] <NSThread: 0x7faa8d4187c0>{number = 2, name = (null)}👌
2021-03-09 16:08:52.385947-0800 xctest[43085:14812747] 👌👌👌👌

第二个dispatch_group_async不应该永远不调度吗?因为锁是由线程#1持有的。然而,我看到NSLog在控制台中打印出来。

调用dispatch_group_async复制提交的块并立即返回。在这种情况下,当最外层的dispatch_group_async返回时,最外层的@synchronized作用域退出,并且在提交的块执行之前释放互斥锁。

最新更新