Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why calling dispatch_sync in current queue not cause deadlock

the apple document says:(concurrencyProgrammingGuide,page49) Important: You should never call the dispatch_sync or dispatch_sync_f function from a task that is executing in the same queue that you are planning to pass to the function. This is particularly important for serial queues, which are guaranteed to deadlock, but should also be avoided for concurrent queues.

but the code here not cause a deadlock, since i have ran it many times:

    dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(concurrentQueue, ^(){
    NSLog(@"in outer queue: %@", [NSThread currentThread]);
    dispatch_sync(concurrentQueue, ^(){
        NSLog(@"do someting thread: %@", [NSThread currentThread]);
    });
});

Yet,we all know,in main thread context, if we execute the code below,it will cause deadlock in main thread. so i am confused why calling dispatch_sync in the same thread, one not deadlock(the code above), the other opposite(the code below)?

        dispatch_sync(dispatch_get_main_queue(), ^{
        NSLog(@"________update__UI");
    });
like image 494
yayamimi Avatar asked Dec 04 '25 14:12

yayamimi


1 Answers

dispatch_get_global_queue() returns a system-defined global concurrent queue.

like image 58
Droppy Avatar answered Dec 07 '25 04:12

Droppy