Getting Started with Swift Concurrency: Task, Actor, Async/Await, and the Threading Model
Swift concurrency is the modern asynchronous programming model introduced in iOS 15+. Through Task, Actor, and the async/await syntax, it offers a safer and more ergonomic approach to concurrency.
The Evolution of Swift’s Concurrency Approaches
Swift’s concurrency story has gone through three main stages.
GCD (Grand Central Dispatch)
GCD was Apple’s earliest concurrency solution, managing task execution via queues:
DispatchQueue.global().async {
print("Running on a background thread")
}
DispatchQueue.main.async {
print("Back on the main thread to update the UI")
}
Operation / OperationQueue
Operation provides a more object-oriented form of concurrency than GCD, supporting cancellation, dependencies, and reuse:
let queue = OperationQueue()
queue.addOperation {
print("Task 1")
}
Swift Concurrency (Recommended)
Swift Concurrency is the new approach Apple recommends on iOS 15+. Its async/await syntax avoids callback hell:
func fetchData() async -> String {
return "result"
}
Task {
let data = await fetchData()
print(data)
}
Core Concepts and the Execution Model
Swift concurrency rests on three core concepts: Task, async/await, and Actor. Unlike the traditional threading model, Swift concurrency schedules at the level of tasks, with threads abstracted away as an implementation detail.
Core Concepts
Task: a unit of concurrent work — analogous to a Runnable or Callable in Java.
async/await: keywords that mark asynchronous functions, letting a function suspend while waiting for a result instead of blocking a thread.
Actor: provides a serialized execution context, ensuring its internal state can’t be accessed by multiple tasks at once — giving you concurrency safety.
The Execution Model
Characteristics of Swift’s concurrency execution model:
- Task-level scheduling: async/await schedules at the task level; threads are an implementation detail.
- Cooperative scheduling: when a task hits
await, it voluntarily suspends and yields its thread to other tasks. - A system-managed thread pool: rather than spawning a new thread per task, it uses a thread pool managed by the system.
The Cooperative Scheduling Mechanism
func fetchData() async -> String {
// Simulate a network request
try? await Task.sleep(nanoseconds: 2_000_000_000) // 2 seconds
return "data"
}
Task {
print("Starting the request")
let result = await fetchData()
print("Got result: \(result)")
}
Execution flow:
- The Task begins executing.
- It hits
await fetchData()and suspends. - The system thread is free to run other Tasks.
- After 2 seconds
fetchDatacompletes, and the Task is resumed.
Task
A Task is the fundamental unit of work in Swift concurrency, and can be created almost anywhere: at global scope, inside a function, or inside an Actor. Its main job is to start asynchronous execution and it may contain await calls:
// Creating a Task inside a function
func performAsyncWork() {
Task {
let result = await fetchData()
print("Result: \(result)")
}
}
A comparison:
- Thread: an OS-level execution context — heavyweight.
- Actor: an execution context that isolates state and guarantees serial access.
- Task: an asynchronous execution context — lightweight, managed by the Swift runtime.
A Task inherits the current execution context / calling environment by default.
Cancelling a Task
cancel() merely signals cancellation to the task; the task itself must actively call Task.checkCancellation() (or some other operation that throws CancellationError, such as Task.sleep()) to respond to it.
If you want the result from outside, use try await task.value — if the task was cancelled, this throws CancellationError.
let task = Task {
for i in 1...5 {
try Task.checkCancellation() // Check whether we've been cancelled
print("Executing step \(i)")
try await Task.sleep(nanoseconds: 1_000_000_000)
}
return "done"
}
// Cancel the task
task.cancel()
TaskGroup
Use a TaskGroup (a concurrent group of tasks) when you need to run several async tasks at once and wait for them all to finish:
func fetchAllData() async -> [String] {
await withTaskGroup(of: String.self) { group -> [String] in
group.addTask { await fetchData(id: 1) }
group.addTask { await fetchData(id: 2) }
var results = [String]()
for await result in group {
results.append(result)
}
return results
}
}
The code above collects results in the order they return. If you want to preserve the original id order instead, write:
func fetchAllData() async -> [String] {
async let data1 = fetchData(id: 1)
async let data2 = fetchData(id: 2)
return await [data1, data2]
}
Actor
The Actor is the core mechanism for thread safety in Swift concurrency. Each Actor has its own execution context, ensuring its internal state can’t be accessed by multiple tasks simultaneously.
actor Counter {
private var value = 0
func increment() async {
value += 1
}
func getValue() async -> Int {
return value
}
}
How an Actor Works
An Actor guarantees thread safety through these mechanisms:
- Each Actor has its own execution context (an Executor).
- All access to the Actor’s internal state runs through a serial queue.
- External access to the Actor must use
await.
An Actor is essentially an implicit serial executor. When an Actor is created, the Swift runtime assigns it an executor that maintains an internal task queue, ensuring tasks run in order.
Tracing the Execution Flow
actor Counter {
var value = 0
func increment() { value += 1 } // Note: async is not necessarily required here
}
// Calling from outside
Task {
await counter.increment() // ...but await is required
}
Execution flow:
- The compiler recognizes
await counter.increment()as a cross-Actor call. - It wraps the call into a continuation and places it on Counter’s task queue.
- If Counter is currently idle, it runs immediately; otherwise it waits for the previous task to finish.
increment()runs, modifiesvalue, and returns the result.
A continuation is the object the Swift concurrency runtime creates when it encounters await. It represents “everything needed to resume execution from the suspension point”, including:
- Program state (local variables, the stack frame)
- The code that should continue running after the suspension point
- The scheduling context (the task, the executor/actor)
- The resume interface (the
resume(...)method)
Actor Access Rules
Internal access: inside the Actor you can access its state directly, without await, because you already hold the execution right.
External access: must use await, because you need to wait for the Actor’s serial access right — even if the method itself is synchronous.
So within an Actor context, await doesn’t mean “wait for an async operation to finish” — it means “wait for the Actor’s serial access right.” This is what guarantees thread-safe access to the Actor’s internal state, and it’s also why increment() itself is synchronous yet external access must still use await.
A Closer Look at Some Examples
A slightly more involved example:
actor Counter {
var value = 0
func incrementWithTask() {
Task {
await self.increment() // The internal call still needs await
}
}
func increment() async {
value += 1
}
}
Analysis:
incrementWithTask()is a synchronous method that doesn’t touch the Actor’s internal state, so calling it doesn’t requireawait.- It spins up a Task internally to run the async logic.
- The caller returns immediately; the async work runs in the background.
Likewise, calling incrementWithTask() here needs no await:
func incrementWithTask() {
print("before task") // Runs synchronously
Task {
await self.increment() // Runs asynchronously
}
print("after task") // Synchronous, returns immediately
}
But this version does require it:
func incrementWithTask() {
print(value) // Compile error!
Task {
await self.increment()
}
}
Why the error: value is the Actor’s isolated state and can’t be accessed directly from outside a Task. You can only reach an Actor’s isolated state via an await call or from inside a Task.
Summary of the Actor Concurrency Mechanism
Swift’s Actor mechanism guarantees thread safety through cooperation between the compiler and the runtime.
The compiler guarantees:
- Tracking which methods access the Actor’s isolated state
- Ensuring all access to the Actor’s internal state happens in an async-safe context
- Forcing external access to use
await
The runtime guarantees:
- Maintaining the Actor’s serial execution queue
- Ensuring access runs in order, achieving thread safety
- Managing task scheduling and context switching
MainActor and the Main Thread
@MainActor is a special Actor provided by Swift Concurrency that ensures the associated code runs on the main thread. The common use cases are UI updates and accessing main-thread resources.
Example:
@MainActor
func updateUI() {
// This always runs on the main thread
label.text = "Hello"
}
Task {
await updateUI() // The compiler ensures we switch to the main thread
}
Be careful not to block the main thread. A bad approach — doing expensive work on the main thread:
@MainActor
func badExample() {
Thread.sleep(forTimeInterval: 2) // Blocks the main thread
}
This is also wrong, because a Task inherits the calling environment by default and will therefore run on the main thread:
@MainActor
func badExample2() {
Task {
Thread.sleep(forTimeInterval: 2) // Blocks the main thread
}
}
The right approach: use Task.detached to run the expensive work on a background thread:
@MainActor
func Example() {
Task.detached {
// Expensive background work
Thread.sleep(forTimeInterval: 2)
await MainActor.run {
// Update the UI
}
}
}
Swift 并发编程是 iOS 15+ 引入的现代异步编程范式,通过 Task、Actor 和 async/await 语法提供了更安全、更易用的并发解决方案。
Swift 并发方案演进
Swift 的并发编程经历了三个主要阶段:
GCD(Grand Central Dispatch)
GCD 是苹果最早提供的并发解决方案,基于队列管理任务执行:
DispatchQueue.global().async {
print("在后台线程执行")
}
DispatchQueue.main.async {
print("回到主线程更新UI")
}
Operation / OperationQueue
Operation 提供了比 GCD 更面向对象的并发管理,支持任务取消、依赖关系和复用:
let queue = OperationQueue()
queue.addOperation {
print("任务1")
}
Swift Concurrency(推荐)
Swift Concurrency 是苹果在 iOS 15+ 推荐的新方案,通过 async/await 语法避免回调地狱:
func fetchData() async -> String {
return "结果"
}
Task {
let data = await fetchData()
print(data)
}
核心概念和执行模型
Swift 并发编程基于三个核心概念:Task、async/await 和 Actor。与传统的线程模型不同,Swift 并发采用任务级别的调度,线程作为底层实现细节被抽象化。
核心概念
Task:表示一个并发执行的工作单元,相当于在 Java 里的 Runnable 或 Callable。
async/await:标记异步函数的关键字,允许函数在等待结果时挂起而不阻塞线程。
Actor:提供一个串行化的执行上下文,确保其内部状态不会被多个任务同时访问,实现并发安全。
执行模型
Swift 并发执行模型特点:
- 任务级调度:Swift 的 async/await 基于任务级别调度,线程是底层实现细节
- 协作式调度:当遇到 await 时,任务会主动挂起,让出线程给其他任务
- 系统线程池:使用系统管理的线程池,而非为每个任务创建新线程
协作式调度机制
func fetchData() async -> String {
// 模拟网络请求
try? await Task.sleep(nanoseconds: 2_000_000_000) // 2秒
return "数据"
}
Task {
print("开始请求")
let result = await fetchData()
print("拿到结果: \(result)")
}
执行流程:
- Task 开始执行
- 遇到 await fetchData(),Task 挂起
- 系统线程可以去执行其他 Task
- 2秒后 fetchData 完成,Task 被唤醒继续执行
Task
Task 是 Swift 并发编程的基础工作单元,可以在任何地方创建:全局作用域,函数内部,Actor 内部。Task 的主要作用是启动异步执行,可以包含 await 调用:
// 在函数中创建 Task
func performAsyncWork() {
Task {
let result = await fetchData()
print("结果: \(result)")
}
}
对比:
- Thread:操作系统级的执行上下文,重量级。
- Actor:隔离状态的执行上下文,保证串行访问。
- Task:异步的执行上下文,轻量级,由 Swift runtime 管理。
Task 会默认继承当前的执行上下文/调用环境。
Task 取消
cancel() 只是向任务发送取消信号,任务必须主动调用 Task.checkCancellation() 或其他抛出 CancellationError 的操作(比如 Task.sleep())来响应取消。
如果想在外部获取任务结果,需要用 try await task.value,此时如果任务被取消,会抛出 CancellationError。
let task = Task {
for i in 1...5 {
try Task.checkCancellation() // 检查是否被取消
print("执行第 \(i) 步")
try await Task.sleep(nanoseconds: 1_000_000_000)
}
return "完成"
}
// 取消任务
task.cancel()
TaskGroup
TaskGroup(并发任务组),当需要同时执行多个异步任务并等待它们完成时使用:
func fetchAllData() async -> [String] {
await withTaskGroup(of: String.self) { group -> [String] in
group.addTask { await fetchData(id: 1) }
group.addTask { await fetchData(id: 2) }
var results = [String]()
for await result in group {
results.append(result)
}
return results
}
}
上面这种写法是按照返回结果的顺序收集的数据,如果想要保持这种id顺序,可以写:
func fetchAllData() async -> [String] {
async let data1 = fetchData(id: 1)
async let data2 = fetchData(id: 2)
return await [data1, data2]
}
Actor
Actor 是 Swift 并发编程中实现线程安全的核心机制。每个 Actor 都有独立的执行上下文,确保其内部状态不会被多个任务同时访问。
actor Counter {
private var value = 0
func increment() async {
value += 1
}
func getValue() async -> Int {
return value
}
}
Actor 原理
Actor 通过以下机制保证线程安全:
- 每个 Actor 都有独立的执行上下文(Executor)
- 所有对 Actor 内部状态的访问都通过串行队列执行
- 外部访问 Actor 必须使用 await 关键字
Actor 本质上是一个隐式的串行执行器(Serial Executor)。每个 Actor 在创建时,Swift 运行时会为其分配一个执行器,该执行器内部维护一个任务队列,确保任务按顺序执行。
执行流程分析
actor Counter {
var value = 0
func increment() { value += 1 } // 注意这里,并不一定要加 async
}
// 外部调用
Task {
await counter.increment() // 但必须加 await
}
执行流程:
- 编译器识别
await counter.increment()为跨 Actor 调用 - 将调用包装成 continuation,放入 Counter 的任务队列
- 如果 Counter 当前无任务执行,立即执行;否则等待前一个任务完成
- 运行 increment(),修改 value,返回结果
这里的 Continuation 是 Swift 并发运行时在遇到 await 时生成的对象,表示“从挂起点恢复执行所需的一切信息”,包括:
- 程序状态(局部变量、栈帧)
- 挂起点之后需要继续执行的代码
- 调度上下文(任务、执行器/actor)
- 恢复接口(
resume(...)方法)
Actor 访问规则
内部访问:在 Actor 内部可以直接访问其状态,无需 await,因为说明已经拿到执行权
外部访问:必须使用 await 关键字,因为需要等待 Actor 的串行访问权,即使方法本身是同步的。
所以,在 Actor 上下文中,await 并非等待异步操作完成,而是等待 Actor 的串行访问权。这确保了 Actor 内部状态的线程安全访问。这也是为什么 increment() 本身是同步的,但外部访问必须加 await。
示例探讨
稍微更复杂一点的例子:
actor Counter {
var value = 0
func incrementWithTask() {
Task {
await self.increment() // 内部调用需要 await
}
}
func increment() async {
value += 1
}
}
分析:
incrementWithTask()是同步方法,并且没有修改Actor内部状态,因此调用时不需要 await- 内部创建 Task 来执行异步逻辑
- 调用方立即返回,异步逻辑在后台执行
相同地,这种情况调用 incrementWithTask() 也无需 await:
func incrementWithTask() {
print("before task") // 同步执行
Task {
await self.increment() // 异步执行
}
print("after task") // 同步执行,立即返回
}
但是,这种情况就需要:
func incrementWithTask() {
print(value) // 编译错误!
Task {
await self.increment()
}
}
错误原因:value 是 Actor 的隔离状态,在 Task 外部无法直接访问。只有通过 await 调用或 Task 内部才能访问 Actor 的隔离状态。
Actor 并发机制总结
Swift 的 Actor 并发机制通过编译器和运行时的协同工作来保证线程安全:
编译器保证:
- 追踪哪些方法访问了 Actor 的隔离状态
- 确保所有对 Actor 内部状态的访问都在异步安全的上下文中执行
- 强制外部访问使用 await 关键字
运行时保证:
- 维护 Actor 的串行执行队列
- 确保访问按顺序执行,实现线程安全
- 管理任务调度和上下文切换
MainActor 与主线程
@MainActor 是 Swift Concurrency 提供的特殊 Actor,确保相关代码在主线程执行。常用场景是 UI 更新和主线程资源访问。
示例:
@MainActor
func updateUI() {
// 这里一定在主线程执行
label.text = "Hello"
}
Task {
await updateUI() // 编译器确保切换到主线程执行
}
注意避免阻塞主线程。错误做法:在主线程执行耗时操作:
@MainActor
func badExample() {
Thread.sleep(forTimeInterval: 2) // 阻塞主线程
}
这样写也不行,因为 Task 会默认继承调用环境,即会在主线程运行:
@MainActor
func badExample2() {
Task {
Thread.sleep(forTimeInterval: 2) // 阻塞主线程
}
}
正确做法:使用 Task.detached 在后台线程执行耗时操作:
@MainActor
func Example() {
Task.detached {
// 后台耗时操作
Thread.sleep(forTimeInterval: 2)
await MainActor.run {
// 更新 UI
}
}
}