I just read this on objc.io Going Fully Asynchronous but can't find good explanation
dispatch_queue_t queueA; // assume we have this
dispatch_sync(queueA, ^(){ // (a)
dispatch_sync(queueA, ^(){ // (b)
foo();
});
});
Once we hit the second dispatch_sync we’ll deadlock: We can’t dispatch onto queueA, because someone (the current thread) is already on that queue and is never going to leave it.
As long as I understand
dispatch_sync
just add the work item (I avoid using the word "block" as it may confuse) to the queueA, then this work item will be send to queueA 's target queue, then GCD will preserve a thread threadWorkItem for this work item- When I reach (b), I'm in the thread threadWorkItem (suppose threadWorkItem is the name of this thread), so I think enqueuing another work item to queueA is no problem. But some people say that at this time, queueA is preserved, queueA is blocked -> causes deadlock, which confuses me
I already read many threads related to this, such as Deadlock with dispatch_sync, Why can't we use a dispatch_sync on the current queue?, Why is this dispatch_sync() call freezing?, ... but can't find good explanation. Some say dispatch_sync
blocks the queue, some say it blocks the current thread, ... :(
So why does it cause deadlock ?