FELIX GAO
FELIX GAO

Reputation: 11

Objective C nested @synchronized in different threads

I have a question for this test senario:

- (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);
}

And here is the output:

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] 👌👌👌👌

Shouldn't the second dispatch_group_async never dispatch since the lock is held by thread #1. However I see that NSLog get printed in the console.

Upvotes: 1

Views: 45

Answers (1)

sbooth
sbooth

Reputation: 16976

Calls to dispatch_group_async copy the submitted block and return immediately. In this case when the outermost dispatch_group_async returns the outermost @synchronized scope exits and the mutex is released before the submitted block is executed.

Upvotes: 3

Related Questions