6

Swift 5.5 Brings Async/Await and Actor Support

 3 years ago
source link: https://www.infoq.com/news/2021/06/swift-async-await-actors/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Swift 5.5 Brings Async/Await and Actor Support

Jun 13, 2021 2 min read

At WWDC21, Apple has introduced Swift 5.5, available in beta. Among its new features, one of the most anticipated is better concurrency support using aysnc/await and actors.

Asynchronous functions aim to make concurrent Swift code easier to write and understand, says Apple. Traditionally, Swift used closures and completion handlers to handle asynchronous operations. As it is known, this approach quickly leads to "callback hell" when your code has many asynchronous operations, or control flow gets complicated.

Swift asynchronous functions bring instead coroutines to the language.

Functions can opt into being async, allowing the programmer to compose complex logic involving asynchronous operations using the normal control-flow mechanisms. The compiler is responsible for translating an asynchronous function into an appropriate set of closures and state machines.

The following code snippet shows how you can declare and call async functions as if they were synchronous:

func loadWebResource(_ path: String) async throws -> Resource
func decodeImage(_ r1: Resource, _ r2: Resource) async throws -> Image
func dewarpAndCleanupImage(_ i : Image) async throws -> Image

func processImageData() async throws -> Image {
  let dataResource  = try await loadWebResource("dataprofile.txt")
  let imageResource = try await loadWebResource("imagedata.dat")
  let imageTmp      = try await decodeImage(dataResource, imageResource)
  let imageResult   = try await dewarpAndCleanupImage(imageTmp)
  return imageResult
}

While asynchronous functions appear to greatly simplify concurrency management, they do not rule out the possibility of deadlocks or state corruption. In particular, programmers should be aware of suspension points that async functions introduce. At a suspension point, a function relinquish its thread. This happens, for example, when you call an asynchronous function associated with a different execution context. To avoid the risk of deadlocks or data corruption, async functions should avoid calling functions that may block their thread.

For example, acquiring a mutex can only block until some currently-running thread gives up the mutex; this is sometimes acceptable but must be used carefully to avoid introducing deadlocks or artificial scalability problems. In contrast, waiting on a condition variable can block until some arbitrary other work gets scheduled that signals the variable; this pattern goes strongly against recommendation.

An interesting evolution of this feature enables calling asynchronous Objective-C APIs, which use completion handlers, using an await expression.

Actors, on the other hand, are an abstraction built on top of async and await to safely access mutable state. In short, actors encapsulate some state and provide a set of methods to access it safely.

Unlike classes, actors allow only one task to access their mutable state at a time, which makes it safe for code in multiple tasks to interact with the same instance of an actor.

This is an examples of a Swift actor:

actor TemperatureLogger {
    let label: String
    var measurements: [Int]
    private(set) var max: Int

    init(label: String, measurement: Int) {
        self.label = label
        self.measurements = [measurement]
        self.max = measurement
    }
}

An actor's methods can be used indifferently synchronously or asynchronously from within the actor, but the compiler will force you to use an async operation to read the actor's state from outside the actor.

If you are interested in learning how Swift concurrency works behind the scenes, understanding how Swift tasks differ from Grand Central Dispatch, and how to write concurrent Swift code with performance in mind, do not miss Apple WWDC session Swift concurrency: Behind the scenes.

Swift 5.5 is currently available as part of Xcode 13 beta, which can be downloaded from Apple developer website.


Recommend

  • 13
    • nick.scialli.me 4 years ago
    • Cache

    Callbacks, Promises, and Async-Await

    Introduction JavaScript touts asynchronous programming as a feature. This means that, if any action takes a while, your program can continue doing other things while the action completes. Once that action is done, you can do somethin...

  • 11

    The danger of async/await and .Result in one picture Sync over async in .NET is always b...

  • 15

    You all might know that async/await is accepted and is available in the main snapshots! Let’s get our hands dirty by trying out some basic example of async/await in Swift. Prerequisites Xcode 12.3 La...

  • 2

    2021-04-06: Interfacing a low-level actor system to Rust async/await, part 1 I've been coding on never-...

  • 8
    • auth0.com 3 years ago
    • Cache

    Async Await in Swift

    This year, WWDC came with a bunch of new features and updates. Maybe one of the most expected was the introduction of the new concurrency system by using async/await syntax. This is a huge improvement in the way that we write asynchronous cod...

  • 11

    Making Network Requests with Async/await in Swift Traditionally, when we want to make a network request, we must use the closure-based URLSession APIs to perform the request asynchronously so that our apps can be respons...

  • 6

    Using Async/Await with AWS Amplify Libraries for Swift by Kyle Lee | on 03 NOV 2022 | in

  • 7

    Swift 中的 Async/Await ——代码实例详解 作者:Swift君 2022-11-21 09:01:00 Swift 中的 async-await 允许结构化并发,这将提高复杂异步代码的可读性。不再需要完成闭包,而在彼此之后调用多个异步方法的可读性也...

  • 6

    Swift并发编程 - 理解 async 和 await 原创  2023-06-30  本文是我学习 Swift 并发编程的第一篇笔记,文章从几个不太好理解的点,介绍了async 和 await 语法关键字的使用方法和内在含义。 async 使用 async 修...

  • 13

    How async/await works internally in Swift How async/await works internally in Swift Published on 28 Sep 2023 async/await in Swift was introduced with iOS 15, and...

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK