MiddleCodeCommonNot answered yet
Predict the console output of these nested queue dispatches
This code runs on the main thread. work is a serial dispatch queue. Determine the exact order in which the five letters print to the console.
Constraints:
- Reason about which calls block and which are deferred to the run loop.
- Assume no other work is queued on the main thread.
let work = DispatchQueue(label: "work")
print("A")
work.sync {
print("B")
DispatchQueue.main.async { print("C") }
print("D")
}
print("E")
Determine the printed order and justify it.
The order is A B D E C. work.sync blocks the main thread and runs the block inline, so B and D print before E. C is queued with main.async, so it runs only after the main thread returns to its run loop — after E.
- ✗Thinking
main.asyncruns its block inline rather than on the next run-loop pass - ✗Believing
work.syncreturns before its block finishes - ✗Assuming a scheduled block runs in the source position where it appears
- →Why can't
Crun while the main thread is still insidework.sync? - →Would the order change if
work.syncwerework.asyncinstead?
The printed order is A B D E C.
// A — prints immediately, synchronously
// work.sync — blocks the main thread and runs the block:
// B — prints
// main.async — queues C on the main thread (does NOT run it now)
// D — prints
// sync returns, the main thread continues:
// E — prints
// the main thread returns to the run loop:
// C — prints last
work.sync blocks the main thread until the block finishes, so B and D come before E. main.async only enqueues C on the main thread; that block cannot run while the main thread is busy inside sync, and only runs once it returns to the run loop — that is, after E.