how does async work

Generated on 8/2/2024

1 search

Async functions in Swift are designed to efficiently handle tasks that may need to wait for other operations to complete, such as reading from a disk or messaging another service. Here’s a detailed explanation of how async functions work:

  1. Suspension and Resumption:

    • When a task is waiting for an asynchronous operation to complete, it suspends to yield the CPU to other tasks that have work to do. This is modeled in code using the async and await keywords. A function that may suspend is marked with the async keyword, and the await keyword is used to indicate that a suspension can occur on that line. (A Swift Tour: Explore Swift’s features and design)
  2. Memory Allocation:

    • Async functions keep their local state on a separate stack from the C stack and are split into multiple functions at runtime. When an async function wants to allocate memory, it asks the task for memory. The stack tries to satisfy that from the current slab, and if it can, the task will mark that part of the slab as used and give it to the function. If the allocation doesn't fit, a new slab is allocated with malloc. Deallocation hands the memory back to the task, where it becomes marked as unused. (Explore Swift performance)
  3. Partial Functions:

    • Async functions are split into partial functions that span the gaps between potential suspension points. For example, if there is one await in the function, it results in two partial functions. The first partial function starts with the entry to the original function and runs until the suspension point. The second partial function picks up after the await. This ensures that only one partial function is on the C stack at a time. (Explore Swift performance)
  4. Concurrency and Actors:

    • Swift provides a feature called actors, which are similar to classes but automatically protect their state by serializing accesses. Calls to actor methods from outside the context of the actor are asynchronous. This helps in managing concurrent accesses safely. (A Swift Tour: Explore Swift’s features and design)
  5. Testing Asynchronous Code:

    • When writing concurrent test code, you can use the same concurrency features in Swift as in production code. The await keyword works the same way in tests, suspending the test and allowing other test code to keep the CPU busy while work is pending. (Go further with Swift Testing)

For a more detailed exploration of async functions, you can refer to the session Explore Swift performance.