I have two code blocks, one using DispatchQueue.main.sync
inside DispatchQueue.main.async
, and another using a customSerialQueue.sync
instead of DispatchQueue.main.sync
. The first block causes a deadlock, while the second doesn't. I'm wondering why this is the case.
Here's the first block of code that deadlocks:
DispatchQueue.main.async {
DispatchQueue.main.sync {
print("this won't print")
}
}
The DispatchQueue.main.sync
call blocks the current thread it's executing on (which is the main thread), until the print
statement executes on the main thread. However, the main thread is already blocked by the DispatchQueue.main.sync
call, resulting in a deadlock.
And here's the second block of code that doesn't deadlock:
let customSerialQueue = DispatchQueue(label: "com.example.serialqueue")
DispatchQueue.main.async {
// main thread
customSerialQueue.sync {
print("this will print") // main thread
}
}
As for my understanding, calling customSerialQueue.sync
reuses the thread (which happens to be the main thread) to run the block. I confirmed it really does by using breakpoints in Xcode. So I assumed this would also lead to deadlock, similar to the case in the first code block.
I wonder what's the difference between the two, and why the second one doesn't deadlock.