Bradley Mackey
Bradley Mackey

Reputation: 7708

Swift Concurrency - non-blocking sleep()?

Swift has access to Darwin's sleep call which is simple to use:

sleep(10) // waits for 10 seconds, but blocks the thread

However, this blocks the current thread. Now that Swift has support for async/await is there a built-in, non-blocking sleep method that does not suspend the current thread?

// what I'm looking for:

func doWork() async {
    // ...
    await sleep(10) // lightweight, does not block thread
    // ... 
}

Upvotes: 3

Views: 1643

Answers (1)

Bradley Mackey
Bradley Mackey

Reputation: 7708

Found it. There's a built-in method on Task (part of the Swift standard library) that offers this sleeping functionality to suspend the current task without blocking the thread. The Swift runtime achieves this by adding a "suspension point" during runtime so the thread will be free to execute other code and will only return to the function when the task resumes.

"Tasks" are a construct offered by Swift's "structured concurrency" to aid with dispatching multiple workloads concurrently. Anyone else interested can read more about it here.

func doWork() async {
    // ...
    await Task.sleep(for: .seconds(1)) // lightweight, does not block thread
    // ... 
}

Upvotes: 6

Related Questions