import Foundation public func foo() { sleep(1) print("B") } print("A") foo() print("C")
In what order do you expect the letters to print?
A B C
We can inline the function call and see what order the statements will be executed:
import Foundation print("A") sleep(1) print("B") print("C")
Instead of calling foo()
directly, let’s schedule foo()
to be executed by adding it to the DispatchQueue
for a background thread asynchronously.
import Foundation public func foo() { sleep(1) print("B") } print("A") DispatchQueue.global(qos: .background).async { foo() } print("C")
In what order will the letters print?
A C B
The C
printed before the B
this time. Why?