what is async stack?

Generated on 8/6/2024

1 search

An async stack in Swift is a specialized stack used by asynchronous functions to manage their local state. Unlike synchronous functions, which allocate their local memory on the C stack, async functions use a separate stack. This is because async functions can suspend execution, and their local state needs to be preserved across these suspension points.

Here are some key points about async stacks:

  1. Separate Stack: Async functions keep their local state on a separate stack from the C stack.
  2. Memory Allocation: Instead of allocating memory from a large contiguous stack, async tasks hold onto one or more slabs of memory. When an async function needs memory, it requests it from the current slab. If the slab is full, a new slab is allocated using malloc.
  3. Partial Functions: Async functions are split into multiple partial functions at runtime, each spanning the gaps between potential suspension points. This allows the function to suspend and resume execution efficiently.
  4. Performance: The allocator used by async tasks is typically faster than malloc because it is only used by a single task and follows a stack discipline.

For a detailed explanation, you can refer to the session Explore Swift performance starting at 24:33.