ios – Why doesn’t calling serialQueue.sync() end in a impasse?

0
1
ios – Why doesn’t calling serialQueue.sync() end in a impasse?


Whereas finding out 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. After I printed the thread that was working the block, it turned out to be the principle thread. This confused me, as a result of the queue wasn’t the principle queue, but the block nonetheless executed on the principle 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 perform executes blocks on the
present thread at any time when attainable, with one exception: Blocks submitted
to the principle dispatch queue all the time run on the principle thread.

Primarily based on this description, I assumed that if the block was certainly executed on the present thread (the principle thread on this case), then a impasse ought to have occurred.

Right here’s the reasoning I had:

  1. The primary thread calls serialQueue.sync(). As a result of it’s synchronous, the principle thread turns into blocked till the block completes.
  2. The block is submitted to the serial queue, which then makes an attempt to execute it on the principle thread (the present thread).
  3. Nevertheless, because the essential thread is already blocked, it wouldn’t be capable to course of the duty, which ought to trigger a impasse.

However opposite to my expectation, no impasse occurred and the code executed simply high-quality. I can’t work out why.

Query.

  1. Why is a block executed on the principle thread though it was submitted to a customized serial queue?
  2. 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?
  3. Can the principle thread nonetheless execute different duties whereas it’s blocked? I want to perceive how precisely the principle thread operates.

LEAVE A REPLY

Please enter your comment!
Please enter your name here