Predict the output
This runs in viewDidLoad (on the main thread). What happens?
print("1")
DispatchQueue.main.sync {
print("2")
}
print("3")Hint 1 of 1
What is the main thread doing while sync waits?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: C 1, then the main thread deadlocks and libdispatch usually crashes the app
Correct. sync waits on the main queue from the main queue.
Why not the others?
- A 1, 2, 3. The closure needs the main thread, which is blocked waiting for it.
- B 1, 3, 2. That is what main.async would print; sync waits.
- D 1, then the app hangs silently forever. It is a deadlock, but GCD detects this case and usually traps instead of hanging.