Sync call serial queue created in main is OK while sync call main queue in main is DEAD-LOCK

69 views Asked by At
int main(void) {
    dispatch_queue_t queue = dispatch_queue_create(“com.somecompany.queue”, nil);
    dispatch_sync(queue, ^{ // task 1
        NSLog(@"Situation 1"); 
    });
    return 0;
}

This is OK run in the main().

//-------------------------------------------

int main(void) {
    dispatch_queue_t queue = dispatch_get_main_queue();
    dispatch_sync(queue, ^{ // task 1
        NSLog(@"Situation 2"); 
    });
    return 0;
}

This is DEAD-LOCK in the main().

//-------------------------------------------

Why situation 1 is OK while situation 2 is DEAD-LOCK ? Both are sync call serial queue in main thread.

Or just because sync() itself run in the main queue ?

1

There are 1 answers

3
Paulw11 On

In the first case you block the main queue until the task has finished executing on the dispatch queue you created, so there is no problem.

In the second case you are trying to dispatch your task on the main queue, but the main queue is blocked by the dispatch_sync, so the submitted closure can't start. The result is a deadlock