Middle — Senior
Determine the order of output of numbers in the program (option 4)
livecode
Task condition
This is a small Swift program that sequentially calls functions printing numbers to the console, and also uses asynchronous and synchronous calls to the main dispatch queue. It is required to determine which numbers will appear in the output and in what order, considering the features of DispatchQueue.main.async and DispatchQueue.main.sync.
func runTask() {
print(5)
DispatchQueue.main.async {
print(10)
}
print(15)
DispatchQueue.main.sync {
print(20)
}
print(25)
}
func runAnotherTask() {
print(30)
}
// Main Thread
runTask()
runAnotherTask()
Note that calling DispatchQueue.main.sync from the main thread leads to a deadlock, so part of the code may not execute.