27.3 · Queue ordering, deadlocks and work items
Queue puzzles are about which lines are ordered by the queue and which merely look ordered. Async never runs inline, a serial queue is first in first out, and a stored work item can quietly own your object.
Mental model. Draw the queue. Async appends and returns; sync waits for its turn; a serial queue runs one block at a time, in order; and only what the queue orders is guaranteed.
Order, blocking and ownership
Nested main-queue async, serial and barrier ordering, self-sync traps and work-item cycles.
- Blocks are scheduled on the main queue from the main thread, and one of them schedules another. In what order do the prints appear?
DispatchQueue.main.async never runs its block inline: it appends the block to the main queue and returns at once. The main queue is first in first out and runs… - On a serial queue, which prints are guaranteed to be ordered, what does a barrier guarantee, and what happens if a block calls sync on its own queue?
A serial queue runs its blocks one at a time in the order they were submitted, so every print inside a block on that queue is ordered relative to the others… - A screen stores a DispatchWorkItem whose closure uses self. Does cancelling the item fix the leak, and what does?
The object owns the item (a stored property) and the item’s closure owns the object (it uses self strongly): a retain cycle, and dropping your last outside…