Whereas learning DispatchQueue, I got here throughout one thing I don’t fairly perceive.
I created a customized serial queue and executed a synchronous block on it. Once I printed the thread that was working the block, it turned out to be the primary thread. This confused me, as a result of the queue wasn’t the primary queue, but the block nonetheless executed on the primary thread.
let serialQueue = DispatchQueue(label: "serial.queue")
serialQueue.sync {
print("present thread = (Thread.present)") // present thread = _NSMainThread
}
Within the documentation for sync(), I discovered the next assertion:
As a efficiency optimization, this operate executes blocks on the
present thread at any time when potential, with one exception: Blocks submitted
to the primary dispatch queue at all times run on the primary thread.
Primarily based on this description, I assumed that if the block was certainly executed on the present thread (the primary thread on this case), then a impasse ought to have occurred.
Right here’s the reasoning I had:
- The primary thread calls serialQueue.sync(). As a result of it’s synchronous, the primary thread turns into blocked till the block completes.
- The block is submitted to the serial queue, which then makes an attempt to execute it on the primary thread (the present thread).
- Nonetheless, for the reason that primary thread is already blocked, it wouldn’t have the ability to course of the duty, which ought to trigger a impasse.
However opposite to my expectation, no impasse occurred and the code executed simply tremendous. I can’t determine why.
Query.
- Why is a block executed on the primary thread regardless that it was submitted to a customized serial queue?
- If, because the documentation suggests, sync() executes on the present thread as an optimization, why doesn’t this result in a impasse on this case?
- Can the primary thread nonetheless execute different duties whereas it’s blocked? I want to perceive how precisely the primary thread operates.