DevPrep

All topics › What does it print? Interview puzzles

GCD puzzle: output order and where is the deadlock?

Senior PRO

Task

The code runs on the main thread (e.g. in main.swift). What gets printed?

let main = DispatchQueue.main
let serial = DispatchQueue(label: "serial")
let concurrent = DispatchQueue(label: "concurrent", attributes: .concurrent)

main.async {
    print(1)
}

main.async {
    print(2)
    serial.async { print(3) }
    serial.sync {
        print(4)
        concurrent.sync {
            print(5)
            concurrent.sync { print(6) }
            serial.sync { print(7) }
        }
    }
}

serial.sync { print(8) }

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