【问题标题】:Objective C nested @synchronized in different threadsObjective C在不同线程中嵌套@synchronized
【发布时间】:2021-06-07 22:08:20
【问题描述】:

我有一个关于这个测试场景的问题:

- (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 打印在控制台中。

【问题讨论】:

    标签: objective-c synchronized dispatch


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2015-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多