/*:#localized(key: "SchedulingWithAsync")
 # `async`: schedule it and move on

 To put work on a queue, you call **`async`**. It hands the closure to the
 queue and returns *immediately*: it does **not** wait for the work to
 finish. Your current thread keeps going.

 Because that background work can outlive the top-level code on a Playground
 page, you need to keep the page alive. That's the `needsIndefiniteExecution`
 pattern from the introduction: tell the page to keep running, and call
 `finishExecution()` yourself when the work is done.
 */
//#-editable-code
import Foundation
import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

print("1️⃣ Taking your order")

DispatchQueue.global().async {
    // Pretend this is a slow pour-over on a background barista.
    Thread.sleep(forTimeInterval: 1.0)
    print("3️⃣ ☕️ Pour-over ready (on a background thread)")
    PlaygroundPage.current.finishExecution()
}

print("2️⃣ Counter is free for the next customer")
//#-end-editable-code
/*:#localized(key: "SchedulingWithAsync-2")
 **Watch it run:** the numbers print `1️⃣ 2️⃣ 3️⃣`, not `1️⃣ 3️⃣ 2️⃣`. Line `2️⃣` runs
 *before* the pour-over finishes, because `async` returned right away and let
 the main line keep moving. The pour-over prints a full second later, from a
 background thread. That gap between `2️⃣` and `3️⃣` is exactly the freeze you
 *avoided* by not doing the work inline.

 * callout(Try it): Change the pour-over delay from `1.0` to `0.2` and run
 again. Does `2️⃣` still print before `3️⃣`?

 [Previous](@previous)  |  page 3 of 9  |  [Next: sync: Block Until It's Done](@next)
 */
