Predict the output
What is the print order?
let serial = DispatchQueue(label: "serial")
print("A")
serial.async { print("B") }
serial.sync { print("C") }
print("D")Hint 1 of 2
Serial queues are first in, first out.
Hint 2 of 2
Does sync return before its closure runs?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: B A, B, C, D
Correct. B is queued, C waits behind it, and sync blocks until C is done, so D prints last.
Why not the others?
- A A, C, D, B. B was queued first. A serial queue runs items in order, so C waits for B.
- C A, D, B, C.
syncblocks the caller until C runs, so D can't come before C. - D Unpredictable. Serial queues are FIFO, so the order is guaranteed.