DevPrep

All topics › Multithreading & concurrency

Can you call main.sync from the main thread? What happens?

Junior PRO

The essence

You cannot. DispatchQueue.main.sync { } blocks the current thread until the main queue runs the block. But the main queue is bound to the main thread, which is the one standing in the wait — the classic deadlock of sync onto the queue you are already on.

In practice the app does not hang, it crashes: libdispatch knows the main thread owns the main queue and aborts the process with EXC_BREAKPOINT and the message "BUG IN CLIENT OF LIBDISPATCH: dispatch_sync called on queue already owned by current thread". The same check fires for any custom serial queue:

let queue = DispatchQueue(label: "serial")
queue.async {
    queue.sync { }        // sync onto the queue we are already running on
}

The rest of this answer, with code and interview follow-ups, is in the DevPrep app.

Read the full answer in DevPrep

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store