Concurrency并发
Perform asynchronous operations.
Swift 原生支持结构化的异步和并行代码。
Swift has built-in support for writing asynchronous and parallel code in a structured way. Asynchronous code can be suspended and resumed later, although only one piece of the program executes at a time. Suspending and resuming code in your program lets it continue to make progress on short-term operations like updating its UI while continuing to work on long-running operations like fetching data over the network or parsing files. Parallel code means multiple pieces of code run simultaneously --- for example, a computer with a four-core processor can run four pieces of code at the same time, with each core carrying out one of the tasks. A program that uses parallel and asynchronous code carries out multiple operations at a time, and it suspends operations that are waiting for an external system. The rest of this chapter uses the term concurrency to refer to this common combination of asynchronous and parallel code.
异步代码是能够被暂时挂起并在稍后继续执行的代码,不过在同一时刻中只有一段程序代码执行。通过挂起和恢复代码,你的程序就可以在执行耗时很长的任务时抽空执行一些快速的操作,比如在下载文件、解析文件的过程中更新 UI。并行代码则意味着多段代码可以在同一时刻执行;例如,一台拥有四核处理器的电脑可以同时运行四段代码(每个核心执行一项任务)。一款运用并行和异步代码编写的程序可以同时运行多个任务,且可以在等待外部系统处理时,暂时挂起一些任务。本章剩余的部分将使用并发一词指代异步和并行代码这一常见的组合。
The additional scheduling flexibility from parallel or asynchronous code also comes with a cost of increased complexity. When you write concurrent code, you don't know ahead of time what code will run at the same time, and you might not always know the order that code will run. A common problem in concurrent code happens when multiple pieces of code try to access some piece of shared mutable state --- this is known as a data race. When you use the language-level support for concurrency, Swift detects and prevents data races, and most data races produce a compile-time error. Some data races can't be detected until your code is running; these data races terminate code execution. You use actors and isolation to protect against data races, as described in this chapter.
并发和异步代码在增加调度灵活性的同时也会增加复杂度。在编写并发代码时,你无法事先知道哪些代码会同时运行,也可能不总是知道代码的运行顺序。并发代码中的一个常见问题是当多段代码试图访问某些共享的可变状态时会发生——这被称为数据竞争。当你使用语言级别的并发支持时,Swift 会检测并防止数据竞争,大多数数据竞争会产生编译时错误。有些数据竞争在代码运行之前无法被检测到;这些数据竞争会终止代码执行。你可以使用 actor 和隔离来防止数据竞争,本章将对此进行描述。
Note · 注意
If you've written concurrent code before, you might be used to working with threads. The concurrency model in Swift is built on top of threads, but you don't interact with them directly. An asynchronous function in Swift can give up the thread that it's running on, which lets another asynchronous function run on that thread while the first function is blocked. When an asynchronous function resumes, Swift doesn't make any guarantee about which thread that function will run on.
如果你曾经编写过并发代码的话,那你可能习惯于使用线程。Swift 中的并发模型基于线程,但你不会直接与线程打交道。在 Swift 中,一个异步函数可以交出它在某个线程上的运行权 —— 这样,另一个异步函数在这个函数被阻塞时就能获得此在此线程上的运行权。但是,Swift 并不保证异步函数恢复运行时其将在哪条线程上运行。
Although it's possible to write concurrent code without using Swift's language support, that code tends to be harder to read. For example, the following code downloads a list of photo names, downloads the first photo in that list, and shows that photo to the user:
你当然也可以不用 Swift 原生支持去写并发的代码,但这样代码的可读性会下降。比如,下面的这段代码会拉取一系列图片名称的列表,下载列表中的第一张图片然后展示给用户:
listPhotos(inGallery: "Summer Vacation") { photoNames in
let sortedNames = photoNames.sorted()
let name = sortedNames[0]
downloadPhoto(named: name) { photo in
show(photo)
}
}Even in this simple case, because the code has to be written as a series of completion handlers, you end up writing nested closures. In this style, more complex code with deep nesting can quickly become unwieldy.
即便是编写这样一个简单的案例,代码中都不可避免地需要使用一系列的完成回调,这导致出现了多层嵌套的闭包。可想而知,使用这种方式编写更复杂的代码会产生更深的嵌套,从而使得代码迅速变得臃肿、难以阅读。
Defining and Calling Asynchronous Functions 定义和调用异步函数
An asynchronous function or asynchronous method is a special kind of function or method that can be suspended while it's partway through execution. This is in contrast to ordinary, synchronous functions and methods, which either run to completion, throw an error, or never return. An asynchronous function or method still does one of those three things, but it can also pause in the middle when it's waiting for something. Inside the body of an asynchronous function or method, you mark each of these places where execution can be suspended.
异步函数 或 异步方法 是一种能在运行中被挂起的特殊函数或方法。相比之下,普通的同步函数和方法只能持续运行到完成、抛出错误,或是永远不返回。异步函数或方法也能做到这三件事,但多出了等待其他资源时暂停执行的能力。在异步函数或者方法的代码块中,你需要明确标注这些可以暂停执行的位置。
To indicate that a function or method is asynchronous,
you write the async keyword in its declaration after its parameters,
similar to how you use throws to mark a throwing function.
If the function or method returns a value,
you write async before the return arrow (->).
For example,
here's how you might fetch the names of photos in a gallery:
要将一个函数或方法标记为异步,你需要在函数 / 方法签名的参数列表后边加上 async 关键字 —— 这和使用throws 关键字来标记可抛出错误的函数十分相似。如果你的函数或方法有返回值,你需要将 async 添加在返回箭头 (->) 的前面。比如,下面这段代码会从图库中提取照片名:
func listPhotos(inGallery name: String) async -> [String] {
let result = // ... some asynchronous networking code ...
return result
}For a function or method that's both asynchronous and throwing,
you write async before throws.
对于既是异步又可抛出错误的方法或函数,请将 async 写在 throws 的前面。
When calling an asynchronous method,
execution suspends until that method returns.
You write await in front of the call
to mark the possible suspension point.
This is like writing try when calling a throwing function,
to mark the possible change to the program's flow if there's an error.
Inside an asynchronous method,
the flow of execution can be suspended
only when you call another asynchronous method ---
suspension is never implicit or preemptive ---
which means every possible suspension point is marked with await.
Marking all of the possible suspension points in your code
helps make concurrent code easier to read and understand.
在调用异步方法时,当前方法的执行会被暂时挂起,直到被调用异步方法返回。你需要在调用前增加 await 关键字来标记此处为可能的挂起点(suspension point)。这就和在调用会抛出错误的方法前需要添加 try 一样 —— 为了标记在发生错误时,程序的执行流程可能发生变化。在一个异步方法中,方法只会在调用另一个异步方法时被挂起 —— 挂起永远不会是隐式或抢占式的,所有可能的挂起点都会用 await 明确地标注出来。这样一来,并发代码的可读性就获得了提升。
For example, the code below fetches the names of all the pictures in a gallery and then shows the first picture:
举个例子,下面这段代码会读取图库中所有图片的名称,然后展示第一张图片:
let photoNames = await listPhotos(inGallery: "Summer Vacation")
let sortedNames = photoNames.sorted()
let name = sortedNames[0]
let photo = await downloadPhoto(named: name)
show(photo)Because the listPhotos(inGallery:) and downloadPhoto(named:) functions
both need to make network requests,
they could take a relatively long time to complete.
Making them both asynchronous by writing async before the return arrow
lets the rest of the app's code keep running
while this code waits for the picture to be ready.
由于 listPhotos(inGallery:) 和 downloadPhoto(named:) 这两个方法都需要发起网络请求,他们都可能耗时较长。为这两个函数在返回箭头前加上 async 可以将它们定义为异步函数,从而使得这部分代码在等待图片下载时,程序中的其他部分可以继续运行。
To understand the concurrent nature of the example above, here's one possible order of execution:
为了更好理解上面这段代码的并发本质,下面列举出这段程序其中一种可能的执行顺序:
- The code starts running from the first line
and runs up to the first
await. It calls thelistPhotos(inGallery:)function and suspends execution while it waits for that function to return.
- 代码从第一行开始执行到第一个
await,调用listPhotos(inGallery:)函数并且挂起这段代码的执行,等待这个函数的返回。
- While this code's execution is suspended,
some other concurrent code in the same program runs.
For example, maybe a long-running background task
continues updating a list of new photo galleries.
That code also runs until the next suspension point, marked by
await, or until it completes.
- 当这段代码的执行被挂起时,程序的其他并行代码便获得了继续执行的机会。比如,也许此时后台有一个耗时长的任务会更新其他一些图库。这个新任务会一直执行到下一个被
await的标记的挂起点,或者一直执行到完成。
- After
listPhotos(inGallery:)returns, this code continues execution starting at that point. It assigns the value that was returned tophotoNames.
- 在
listPhotos(inGallery:)返回之后,上面这段代码会从该处继续执行,并把返回值赋给photoNames。
- The lines that define
sortedNamesandnameare regular, synchronous code. Because nothing is markedawaiton these lines, there aren't any possible suspension points.
- 定义
sortedNames和name的两行代码是普通的同步代码。因为并没有被await标记,这里并不会有任何潜在的挂起点。
- The next
awaitmarks the call to thedownloadPhoto(named:)function. This code pauses execution again until that function returns, giving other concurrent code an opportunity to run.
- 接下来的
await标记出现在调用downloadPhoto(named:)的地方。这里会再次暂停这段代码的执行直到函数返回,从而给了其他并行代码执行的机会。
- After
downloadPhoto(named:)returns, its return value is assigned tophotoand then passed as an argument when callingshow(_:).
- 在
downloadPhoto(named:)返回后,它的返回值会被赋给photo,然后在调用show(_:)时作为实参传入。
The possible suspension points in your code marked with await
indicate that the current piece of code might pause execution
while waiting for the asynchronous function or method to return.
This is also called yielding the thread
because, behind the scenes,
Swift suspends the execution of your code on the current thread
and runs some other code on that thread instead.
Because code with await needs to be able to suspend execution,
only certain places in your program can call asynchronous functions or methods:
代码中被 await 标记的挂起点表明当前这段代码可能会暂停等待异步方法或函数的返回。这也被称为让出线程,因为在幕后 Swift 会挂起这段代码在当前线程的执行,转而让其他代码在当前线程执行。因为有 await 标记的代码可以被挂起,所以在程序中只有特定的地方才能调用异步方法或函数:
- Code in the body of an asynchronous function, method, or property.
- 异步函数,方法或变量的内部的代码
- Code in the static
main()method of a structure, class, or enumeration that's marked with@main.
- 静态函数
main()中被打上@main标记的结构体、类或者枚举中的代码
- Code in an unstructured child task, as shown in Unstructured Concurrency below.
- 非结构化的子任务中的代码,之后会在 非结构化并发 中说明
The Task.sleep(for:tolerance:clock:) method
is useful when writing simple code
to learn how concurrency works.
This method suspends the current task for at least the given amount of time.
Here's a version of the listPhotos(inGallery:) function
that uses sleep(for:tolerance:clock:) to simulate waiting for a network operation:
在学习并发编程时, Task.sleep(for:tolerance:clock:) 这个方法非常有用。这个方法会将当前任务挂起至少指定的时长。以下是 listPhotos(inGallery:) 这个函数的另一个版本,它使用 sleep(for:tolerance:clock:) 来模拟等待网络请求:
func listPhotos(inGallery name: String) async throws -> [String] {
try await Task.sleep(for: .seconds(2))
return ["IMG001", "IMG99", "IMG0404"]
}The version of listPhotos(inGallery:) in the code above
is both asynchronous and throwing,
because the call to Task.sleep(until:tolerance:clock:) can throw an error.
When you call this version of listPhotos(inGallery:),
you write both try and await:
这个版本的 listPhotos(inGallery:) 既是异步的,又可能抛出错误,因为 Task.sleep(until:tolerance:clock:) 可能抛出错误。当你调用这个版本的 listPhotos(inGallery:) 时,你需要同时添加 try 和 await:
let photos = try await listPhotos(inGallery: "A Rainy Weekend")Asynchronous functions have some similarities to throwing functions:
When you define an asynchronous or throwing function,
you mark it with async or throws,
and you mark calls to that function with await or try.
An asynchronous function can call another asynchronous function,
just like a throwing function can call another throwing function.
异步函数和可抛出错误的函数有一些相似点:当你定义一个异步或是可抛出错误的函数时,你不仅需要添加 async 或者 throws,还需要在调用这些方法的代码处添加 await 或 try。一个异步函数可以调用另一个异步函数,就像一个可抛出错误的函数也可以调用另一个可抛出错误的函数。
However, there's a very important difference.
You can wrap throwing code in a do-catch block to handle errors,
or use Result to store the error for code elsewhere to handle it.
These approaches let you call throwing functions
from nonthrowing code.
For example:
但是,这里有一个非常重要的区别。你可以用 do-catch 块包裹可抛出错误的代码来处理错误,也可以使用 Result 来存储错误,交由其他地方的代码来处理。这些方法让你可以在不抛出错误的代码中调用可抛出错误的函数。例如:
func availableRainyWeekendPhotos() -> Result<[String], Error> {
return Result {
try listDownloadedPhotos(inGallery: "A Rainy Weekend")
}
}In contrast, there's no safe way to wrap asynchronous code so you can call it from synchronous code and wait for the result. The Swift standard library intentionally omits this unsafe functionality --- trying to implement it yourself can lead to problems like subtle races, threading issues, and deadlocks. When adding concurrent code to an existing project, work from the top down. Specifically, start by converting the top-most layer of code to use concurrency, and then start converting the functions and methods that it calls, working through the project's architecture one layer at a time. There's no way to take a bottom-up approach, because synchronous code can't ever call asynchronous code.
相比之下,并没有什么安全的方式可以让你在同步代码里执行异步代码并等待结果。因此,Swift 的标准库特意舍弃了这样不安全的功能 —— 如果你执意要自己编写这样的逻辑,最终很有可能导致难以排查的数据竞争、线程问题,或是死锁。当你向现有项目添加并发代码时,请自顶向下进行。特别地,请先将最顶层的代码转换为异步的,然后再开始转换被其调用的其他代码,以此类推一层一层地向下转换。自底向上改造代码的方法是不可能的,因为同步代码无法调用异步代码。
Asynchronous Sequences 异步序列
The listPhotos(inGallery:) function in the previous section
asynchronously returns the whole array at once,
after all of the array's elements are ready.
Another approach
is to wait for one element of the collection at a time
using an asynchronous sequence.
Here's what iterating over an asynchronous sequence looks like:
前文的 listPhotos(inGallery:) 方法会在异步地准备好整个数组的所有元素后,一次性返回整个数组;另一种方式是使用异步序列 (asynchronous sequence) 在每个元素就绪的当下都将其返回。下面这段代码展示了如何遍历一个异步序列:
import Foundation
let handle = FileHandle.standardInput
for try await line in handle.bytes.lines {
print(line)
}Instead of using an ordinary for-in loop,
the example above writes for with await after it.
Like when you call an asynchronous function or method,
writing await indicates a possible suspension point.
A for-await-in loop potentially suspends execution
at the beginning of each iteration,
when it's waiting for the next element to be available.
在这个事例中,我们使用 for 和 await 来代替了普通的 for-in 循环。和你调用异步函数或方法一样,在这里 await 也标注了潜在的挂起点。一个 for-await-in 循环在每一轮迭代的开头都有可能挂起,以便等待序列中下一个元素的就绪。
In the same way that you can use your own types in a for-in loop
by adding conformance to the Sequence protocol,
you can use your own types in a for-await-in loop
by adding conformance to the [AsyncSequence] protocol.
正如同你可以在 for-in 循环中通过遵从 Sequence 协议来使用自定义类型一样,你也可以在 for-await-in 循环中通过遵循 [AsyncSequence] 来使用自定义类型。
Calling Asynchronous Functions in Parallel 并行调用异步函数
Calling an asynchronous function with await
runs only one piece of code at a time.
While the asynchronous code is running,
the caller waits for that code to finish
before moving on to run the next line of code.
For example,
to fetch the first three photos from a gallery,
you could await three calls to the downloadPhoto(named:) function
as follows:
使用 await 来调用异步方法时,在同一时刻只会有一段代码运行。在一段异步代码运行的过程中,调用方会先等待其返回,然后才会执行下一行代码。举个例子,如果你想要读取图库中的前三张照片,你可以像下方这样轮流等待三次对 downloadPhoto(named:) 调用的返回:
let firstPhoto = await downloadPhoto(named: photoNames[0])
let secondPhoto = await downloadPhoto(named: photoNames[1])
let thirdPhoto = await downloadPhoto(named: photoNames[2])
let photos = [firstPhoto, secondPhoto, thirdPhoto]
show(photos)This approach has an important drawback:
Although the download is asynchronous
and lets other work happen while it progresses,
only one call to downloadPhoto(named:) runs at a time.
Each photo downloads completely before the next one starts downloading.
However, there's no need for these operations to wait ---
each photo can download independently, or even at the same time.
这种方式有一个显著的缺点:尽管下载过程是异步的,并且其他的任务也可以在下载过程中继续执行,但每次只有一个 downloadPhoto(named:) 的调用会运行 —— 每张照片都只有在上一张照片完成下载后才会开始下载。然而,这些任务其实没有必要相互等待:每张照片都可以独立下载,甚至是在同一时间下载。
To call an asynchronous function
and let it run in parallel with code around it,
write async in front of let when you define a constant,
and then write await each time you use the constant.
要想在调用异步函数时,允许其与周围的代码并行执行,你可以在使用 let 定义一个常量时,在前方添加 async 标注。然后,你需要在使用此常量时,添加 await 标记。
async let firstPhoto = downloadPhoto(named: photoNames[0])
async let secondPhoto = downloadPhoto(named: photoNames[1])
async let thirdPhoto = downloadPhoto(named: photoNames[2])
let photos = await [firstPhoto, secondPhoto, thirdPhoto]
show(photos)In this example,
all three calls to downloadPhoto(named:) start
without waiting for the previous one to complete.
If there are enough system resources available, they can run at the same time.
None of these function calls are marked with await
because the code doesn't suspend to wait for the function's result.
Instead, execution continues
until the line where photos is defined ---
at that point, the program needs the results from these asynchronous calls,
so you write await to pause execution
until all three photos finish downloading.
在这个例子中,所有三次对 downloadPhoto(named:) 的调用都会立即开始,而不等待前一个调用返回。如果系统此时有足够的可用资源,三个下载任务会并行执行。注意到在这三次函数调用中,我们都没有使用 await 标注,因为这些调用并不会导致代码执行挂起。代码持续执行到 photos 被定义的那一行时,你才需要 await 来暂停程序执行,因为程序需要前面的调用结果才能为 photos 赋值。
Here's how you can think about the differences between these two approaches:
你可以这样理解这两种方式的区别:
- Call asynchronous functions with
awaitwhen the code on the following lines depends on that function's result. This creates work that is carried out sequentially. - Call asynchronous functions with
async-letwhen you don't need the result until later in your code. This creates work that can be carried out in parallel. - Both
awaitandasync-letallow other code to run while they're suspended. - In both cases, you mark the possible suspension point with
awaitto indicate that execution will pause, if needed, until an asynchronous function has returned.
- 当后续几行代码依赖于异步函数的结果时,使用
await来调用它。这样创建的工作会按顺序执行。 - 当你在代码稍后的位置才需要结果时,使用
async-let来调用异步函数。这样创建的工作可以并行执行。 await和async-let都允许其他代码在它们被挂起时运行。- 在这两种情况下,你都要用
await标记可能的挂起点,表明执行在需要时会暂停,直到异步函数返回。
You can also mix both of these approaches in the same code.
你也可以在同一段代码中混合使用两种方法。
Tasks and Task Groups 任务和任务组
A task is a unit of work that can be run asynchronously as part of your program. All asynchronous code runs as part of some task. A task itself does only one thing at a time, but when you create multiple tasks, Swift can schedule them to run simultaneously.
一项*任务 (task)*是一个单元的工作,且可以作为程序的一部分异步执行。所有的异步代码都在某一项任务中执行。一项任务本身只能完成一件事情,但当你创建多个任务时,Swift 可以让他们同时运行。
The async-let syntax described in the previous section
implicitly creates a child task ---
this syntax works well when you already know
what tasks your program needs to run.
You can also create a task group
(an instance of TaskGroup)
and explicitly add child tasks to that group,
which gives you more control over priority and cancellation,
and lets you create a dynamic number of tasks.
上一节中的 async-let 会隐式地创建一项子任务 —— 如果你已经知道程序需要执行什么任务,这种语法十分便捷。你也可以创建一个任务组(TaskGroup 的实例)然后显式地向其中添加子任务。这可以让你更好地控制优先级和任务取消,也可以让你动态决定要创建多少任务。
Tasks are arranged in a hierarchy. Each task in a given task group has the same parent task, and each task can have child tasks. Because of the explicit relationship between tasks and task groups, this approach is called structured concurrency. The explicit parent-child relationship between tasks has several advantages:
任务的排列具有层级结构。同一个任务组中的所有任务都具有相同的父任务, 且他们也可以拥有自己的子任务。考虑到任务和任务组之间具有这种显式的关系,我们将这种范式称为结构化并发 (structured concurrency)。这种任务间的显式父 - 子关系有几种优势:
- In a parent task, you can't forget to wait for its child tasks to complete.
- 在父任务中,你不会忘记等待其子任务完成。
- When setting a higher priority on a child task, the parent task's priority is automatically escalated.
- 当给子任务设置更高的优先级时,父任务的优先级会自动提升。
- When a parent task is canceled, each of its child tasks is also automatically canceled.
- 当父任务被取消时,它的每个子任务也会被自动取消。
- Task-local values propagate to child tasks efficiently and automatically.
- 任务局部值(task-local value)会高效且自动地传递给子任务。
Here's another version of the code to download photos that handles any number of photos:
在下面这个代码示例中,我们可以处理任意数量的照片下载任务:
await withTaskGroup(of: Data.self) { group in
let photoNames = await listPhotos(inGallery: "Summer Vacation")
for name in photoNames {
group.addTask {
return await downloadPhoto(named: name)
}
}
for await photo in group {
show(photo)
}
}The code above creates a new task group, and then creates child tasks to download each photo in the gallery. Swift runs as many of these tasks concurrently as conditions allow. As soon as a child task finishes downloading a photo, that photo is displayed. There's no guarantee about the order that child tasks complete, so the photos from this gallery can be shown in any order.
上面的代码创建了一个新的任务组,并创建了一些子任务,每个任务会下载一张照片。Swift 会在条件许可的情况下,尽可能多地并行执行这些任务。在某一项子任务完成下载后,其对应的照片就会立即被显示出来。不过,这些子任务会以任意顺序完成执行,所以这些照片的最终展示顺序也会是随机的。
Note · 注意
If the code to download a photo could throw an error,
you would call withThrowingTaskGroup(of:returning:body:) instead.
如果下载照片的代码可能抛出错误,你需要调用 withThrowingTaskGroup(of:returning:body:)。
In the code listing above,
each photo is downloaded and then displayed,
so the task group doesn't return any results.
For a task group that returns a result,
you add code that accumulates its result
inside the closure you pass to withTaskGroup(of:returning:body:).
在上面的代码中,每张照片都会被下载然后展示出来,所以任务组没有返回值。对于需要返回结果的任务组,你可以在传递给 withTaskGroup(of:returning:body:) 的闭包中,编写聚合任务结果的逻辑。
let photos = await withTaskGroup(of: Data.self) { group in
let photoNames = await listPhotos(inGallery: "Summer Vacation")
for name in photoNames {
group.addTask {
return await downloadPhoto(named: name)
}
}
var results: [Data] = []
for await photo in group {
results.append(photo)
}
return results
}Like the previous example,
this example creates a child task for each photo to download it.
Unlike the previous example,
the for-await-in loop waits for the next child task to finish,
appends the result of that task to the array of results,
and then continues waiting until all child tasks have finished.
Finally,
the task group returns the array of downloaded photos
as its overall result.
如同之前的范例,这个示例中为每张照片创建了一个下载子任务。与之前不同的是,这里的 for-await-in 循环会等待下一个子任务结束,将其的结果插入到结果数组中,然后继续等待所有子任务完成。最后,这个任务组会将所有下载完毕的照片数组作为一个整体返回。
Task Cancellation 任务取消
Swift concurrency uses a cooperative cancellation model. Each task checks whether it has been canceled at the appropriate points in its execution, and responds to cancellation appropriately. Depending on what work the task is doing, responding to cancellation usually means one of the following:
Swift 中的并发使用的是「协作取消」模型:每个任务都应当在合适的位置检查其是否已被取消,然后对取消指令做出合理的响应。取决于任务所执行工作的性质,通常有这几种方式来响应取消指令:
- Throwing an error like
CancellationError - Returning
nilor an empty collection - Returning the partially completed work
- 抛出类似
CancellationError的错误 - 返回
nil或是一个空的集合 - 返回部分完成的工作
Downloading pictures could take a long time
if the pictures are large or the network is slow.
To let the user stop this work,
without waiting for all of the tasks to complete,
the tasks need to check for cancellation and stop running if they are canceled.
There are two ways a task can do this:
by calling the Task.checkCancellation() type method,
or by reading the Task.isCancelled type property.
Calling checkCancellation() throws an error if the task is canceled;
a throwing task can propagate the error out of the task,
stopping all of the task's work.
This has the advantage of being simple to implement and understand.
For more flexibility, use the isCancelled property,
which lets you perform clean-up work as part of stopping the task,
like closing network connections and deleting temporary files.
如果图片较大或网络较慢,图片下载可能耗时非常长。要允许用户取消这项事务,而不必等待所有任务完成,这些任务必须要检查取消指令,并在收到指令时停止运行。有两种方式可以做到这件事:调用 Task.checkCancellation() 方法,或是检查 Task.isCancelled 属性。如果任务已被取消,调用 checkCancellation() 会抛出错误;一项可抛错误的任务可以将错误向外扩散,并停止任务中的所有工作。这样做的好处是代码编写简单、理解成本更低。要获得更多的灵活度,你可使用 isCancelled 属性,这样你就可以在停止任务的过程中,做一些例如关闭网络连接、清理临时文件的清理工作。
let photos = await withTaskGroup { group in
let photoNames = await listPhotos(inGallery: "Summer Vacation")
for name in photoNames {
let added = group.addTaskUnlessCancelled {
Task.isCancelled ? nil : await downloadPhoto(named: name)
}
guard added else { break }
}
var results: [Data] = []
for await photo in group {
if let photo { results.append(photo) }
}
return results
}The code above makes several changes from the previous version:
上面这段代码相比前一个版本有几个变动:
- Each task is added using the
TaskGroup.addTaskUnlessCancelled(priority:operation:)method, to avoid starting new work after cancellation.
- 每个任务都使用
TaskGroup.addTaskUnlessCancelled(priority:operation:)方法来添加,以避免在取消之后开始新的工作。
- After each call to
addTaskUnlessCancelled(priority:operation:), the code confirms that the new child task was added. If the group is canceled, the value ofaddedisfalse--- in that case, the code stops trying to download additional photos.
- 每次调用
addTaskUnlessCancelled(priority:operation:)之后,这段代码都会确认新的子任务确实已经添加。如果任务组已被取消,added的值为false——这种情况下,代码会停止尝试下载更多照片。
- Each task checks for cancellation
before starting to download the photo.
If it has been canceled, the task returns
nil.
- 每个任务都会在开始下载照片之前检查是否已被取消。如果已被取消,任务返回
nil。
- At the end,
the task group skips
nilvalues when collecting the results. Handling cancellation by returningnilmeans the task group can return a partial result --- the photos that were already downloaded at the time of cancellation --- instead of discarding that completed work.
- 最后,任务组在收集结果时会跳过
nil值。通过返回nil来处理取消,意味着任务组可以返回部分结果——即在取消时已经下载好的照片——而不是丢弃这些已完成的工作。
Note · 注意
To check whether a task has been canceled from outside that task,
use the Task.isCancelled instance property
instead of the type property.
若要在一项任务之外检查这项任务是否已被取消,请使用 Task.isCancelled 实例属性,而不是类属性。
For work that needs immediate notification of cancellation,
use the withTaskCancellationHandler(operation:onCancel:isolation:) function.
For example:
如果你的工作需要在被取消时立即收到通知,可以使用 withTaskCancellationHandler(operation:onCancel:isolation:) 函数。例如:
let task = Task {
await withTaskCancellationHandler {
// ...
} onCancel: {
print("Canceled!")
}
}
// ... some time later...
task.cancel() // Prints "Canceled!"When using a cancellation handler, task cancellation is still cooperative: The task either runs to completion or checks for cancellation and stops early. Because the task is still running when the cancellation handler starts, avoid sharing state between the task and its cancellation handler, which could create a race condition.
在你使用取消回调时,任务取消依然是协作的:任务要么一直执行到完成,要么主动检查取消指令并提早停止。因为在取消回调开始执行时,任务本身依然还在运行,请注意避免在任务和取消回调之间共享状态 —— 这可能导致数据竞争。
Unstructured Concurrency 非结构化并发
In addition to the structured approaches to concurrency described in the previous sections, Swift also supports unstructured concurrency. Unlike tasks that are part of a task group, an unstructured task doesn't have a parent task. You have complete flexibility to manage unstructured tasks in whatever way your program needs, but you're also completely responsible for their correctness.
除了像前文所述那样以结构化的方式编写并发逻辑,Swift 也支持非结构化并发。不像从属于某个任务组的任务,一项非结构化的任务没有父任务。管理非结构化任务时,你将拥有最大的灵活性,可以按任意方式组织他们。但是,你也将需要对他们的正确性承担全部责任。
To create an unstructured task
that runs similarly to the surrounding code,
call the Task.init(name:priority:operation:) initializer.
The new task defaults to running with
the same actor isolation, priority, and task-local state as the current task.
To create an unstructured task
that's more independent from the surrounding code,
known more specifically as a detached task,
call the Task.detached(name:priority:operation:) static method.
The new task defaults to running without any actor isolation
and doesn't inherit the current task's priority or task-local state.
Both of these operations return a task that you can interact with ---
for example, to wait for its result or to cancel it.
要创建一个与周围代码运行方式类似的非结构化任务,请调用 Task.init(name:priority:operation:) 构造器。新任务默认会继承当前任务的 actor 隔离、优先级和任务局部状态。要创建一个更独立于周围代码的非结构化任务——更具体地说是分离任务——请调用 Task.detached(name:priority:operation:) 静态方法。新任务默认会在没有任何 actor 隔离的情况下运行,并且不会继承当前任务的优先级或任务局部状态。这两项操作都会返回 task 实例,便于你管理他们。比如,你可以等待他们的返回结果,也可以取消他们:
let newPhoto = // ... some photo data ...
let handle = Task {
return await add(newPhoto, toGalleryNamed: "Spring Adventures")
}
let result = await handle.valueIsolation 隔离
The previous sections discuss approaches for splitting up concurrent work. That work can involve changing shared data, such as an app's UI. If different parts of your code can modify the same data at the same time, that risks creating a data race. Swift protects you from data races in your code: Whenever you read or modify a piece of data, Swift ensures that no other code is modifying it concurrently. This guarantee is called data isolation. There are three main ways to isolate data:
前面的章节讨论了拆分并发工作的方法。这些工作可能涉及修改共享数据,例如应用程序的 UI。如果代码的不同部分可以同时修改相同的数据,就会有产生数据竞争的风险。Swift 可以保护你的代码免受数据竞争的影响:每当你读取或修改一段数据时,Swift 会确保没有其他代码同时修改它。这种保证被称为数据隔离。数据隔离主要有三种方式:
- Immutable data is always isolated. Because you can't modify a constant, there's no risk of other code modifying a constant at the same time you're reading it.
- 不可变数据始终是隔离的。因为你无法修改常量,所以不存在其他代码在你读取常量的同时修改它的风险。
- Data that's referenced by only the current task is always isolated. A local variable is safe to read and write because no code outside the task has a reference to that memory, so no other code can modify that data. In addition, if you capture the variable in a closure, Swift ensures that the closure isn't used concurrently.
- 仅由当前任务引用的数据始终是隔离的。局部变量可以安全地读写,因为任务之外的代码没有对该内存的引用,所以其他代码无法修改该数据。此外,如果你在闭包中捕获该变量,Swift 会确保该闭包不会被并发使用。
- Data that's protected by an actor is isolated if the code accessing that data is also isolated to the actor. If the current function is isolated to an actor, it's safe to read and write data that's protected by that actor because any other code that's isolated to that same actor must wait its turn before running.
- 由 actor 保护的数据是隔离的,前提是访问该数据的代码也隔离到该 actor。如果当前函数隔离到某个 actor,那么读写该 actor 保护的数据是安全的,因为隔离到同一 actor 的任何其他代码都必须等待轮到它才能运行。
The Main Actor 主 Actor
An actor is an object that protects access to mutable data by forcing code to take turns accessing that data. The most important actor in many programs is the main actor. In an app, the main actor protects all of the data that's used to show the UI. The main actor takes turns rendering the UI, handling UI events, and running code that you write that needs to query or update the UI.
Actor 是一个对象,它通过强制代码轮流访问可变数据来保护对可变数据的访问。在许多程序中,最重要的 actor 是主 actor。在应用程序中,主 actor 保护用于显示 UI 的所有数据。主 actor 轮流渲染 UI、处理 UI 事件以及运行需要查询或更新 UI 的代码。
Before you start using concurrency in your code, everything runs on the main actor. As you identify long-running or resource-intensive code, you can move this work off the main actor in a way that's still safe and correct.
在开始在代码中使用并发之前,所有内容都在主 actor 上运行。当你识别出长时间运行或资源密集型的代码时,可以以安全且正确的方式将这些工作移出主 actor。
Note · 注意
The main actor is closely related to the main thread, but they're not the same thing. The main actor has private mutable state, and the main thread serializes access to that state. When you run code on the main actor, Swift executes that code on the main thread. Because of this connection, you might see these two terms used interchangeably. Your code interacts with the main actor; the main thread is a lower-level implementation detail.
主 actor 与主线程密切相关,但它们不是同一回事。主 actor 有私有可变状态,主线程序列化对该状态的访问。当你在主 actor 上运行代码时,Swift 会在主线程上执行该代码。由于这种联系,你可能会看到这两个术语可以互换使用。你的代码与主 actor 交互;主线程是较低级别的实现细节。
There are several ways to run work on the main actor.
To ensure a function always runs on the main actor,
mark it with the @MainActor attribute:
有几种方法可以在主 actor 上运行工作。要确保函数始终在主 actor 上运行,请使用 @MainActor 属性标记它:
@MainActor
func show(_: Data) {
// ... UI code to display the photo ...
}In the code above,
the @MainActor attribute on the show(_:) function
requires this function to run only on the main actor.
Within other code that's running on the main actor,
you can call show(_:) as a synchronous function.
However,
to call show(_:) from code that isn't running on the main actor,
you have to include await and call it as an asynchronous function
because switching to the main actor introduces a potential suspension point.
For example:
在上面的代码中,show(_:) 函数上的 @MainActor 属性要求此函数只能在主 actor 上运行。在主 actor 上运行的其他代码中,你可以将 show(_:) 作为同步函数调用。但是,要从不在主 actor 上运行的代码调用 show(_:),你必须包含 await 并将其作为异步函数调用,因为切换到主 actor 会引入一个潜在的挂起点。例如:
func downloadAndShowPhoto(named name: String) async {
let photo = await downloadPhoto(named: name)
await show(photo)
}In the code above,
both the downloadPhoto(named:) and show(_:) functions
might suspend when you call them.
This code also shows a common pattern:
Perform long-running and CPU-intensive work in the background,
and then switch to the main actor to update the UI.
Because the downloadAndShowPhoto(named:) function isn't on the main actor,
the work in downloadPhoto(named:) also doesn't run on the main actor.
Only the work in show(_:) to update the UI runs on the main actor,
because that function is marked with the @MainActor attribute.
在上面的代码中,downloadPhoto(named:) 和 show(_:) 函数在调用时都可能挂起。这段代码还展示了一个常见模式:在后台执行长时间运行和 CPU 密集型的工作,然后切换到主 actor 更新 UI。因为 downloadAndShowPhoto(named:) 函数不在主 actor 上,downloadPhoto(named:) 中的工作也不在主 actor 上运行。只有 show(_:) 中更新 UI 的工作在主 actor 上运行,因为该函数标记了 @MainActor 属性。
To ensure that a closure runs on the main actor,
you write @MainActor before the capture list and before in,
at the start of the closure.
要确保闭包在主 actor 上运行,请在捕获列表之前和 in 之前、闭包开头写入 @MainActor。
let photo = await downloadPhoto(named: "Trees at Sunrise")
Task { @MainActor in
show(photo)
}The code above is similar to
downloadAndShowPhoto(named:) from the previous code listing,
but the code in this example doesn't wait for the UI update.
You can also write @MainActor on a structure, class, or enumeration
to ensure all of its methods and all access to its properties
run on the main actor:
上面的代码与前面代码清单中的 downloadAndShowPhoto(named:) 类似,但此示例中的代码不等待 UI 更新。你还可以在结构、类或枚举上写入 @MainActor,以确保其所有方法和对其属性的所有访问都在主 actor 上运行:
@MainActor
struct PhotoGallery {
var photoNames: [String]
func drawUI() { /* ... other UI code ... */ }
}The PhotoGallery structure in the code above
draws the photos on screen,
using the names from its photoNames property
to determine which photos to display.
Because photoNames affects the UI,
code that changes it needs to run on the main actor
to serialize that access.
上面代码中的 PhotoGallery 结构在屏幕上绘制照片,使用其 photoNames 属性中的名称来确定要显示哪些照片。因为 photoNames 影响 UI,更改它的代码需要在主 actor 上运行以序列化该访问。
When you're building on top of a framework,
that framework's protocols and base classes
are typically already marked @MainActor,
so you don't usually write @MainActor on your own types in that case.
Here's a simplified example:
在基于框架构建时,该框架的协议和基类通常已经标记了 @MainActor,所以在这种情况下,你通常不需要在自己的类型上写入 @MainActor。这里有一个简化的例子:
@MainActor
protocol View { /* ... */ }
// Implicitly @MainActor
struct PhotoGalleryView: View { /* ... */ }In the code above,
a framework like SwiftUI defines the View protocol.
By writing @MainActor on the protocol declaration,
types like PhotoGalleryView that conform to the protocol
are also implicitly marked @MainActor.
You'd see the same behavior if View were a base class
and PhotoGalleryView were a subclass ---
the subclass would be implicitly marked @MainActor.
在上面的代码中,像 SwiftUI 这样的框架定义了 View 协议。通过在协议声明上写入 @MainActor,像 PhotoGalleryView 这样符合该协议的类型也会隐式地标记为 @MainActor。如果 View 是基类而 PhotoGalleryView 是子类,你会看到相同的行为——子类会隐式地标记为 @MainActor。
In the examples above,
PhotoGallery protects the entire structure on the main actor.
For more fine-grained control,
you can write @MainActor on just the properties or methods
that need to be accessed or run on the main thread:
在上面的例子中,PhotoGallery 在主 actor 上保护整个结构。为了更精细的控制,你可以仅在需要在主线程上访问或运行的属性或方法上写入 @MainActor:
struct PhotoGallery {
@MainActor var photoNames: [String]
var hasCachedPhotos = false
@MainActor func drawUI() { /* ... UI code ... */ }
func cachePhotos() { /* ... networking code ... */ }
}In the version of PhotoGallery above,
the drawUI() method draws the gallery's pictures on screen,
so it needs to be isolated to the main actor.
The photoNames property doesn't directly create the UI,
but it does store state that the drawUI() function uses to draw the UI,
so this property also needs to be accessed only on the main actor.
In contrast,
changes to the hasCachedPhotos property
don't interact with the UI,
and the cachePhotos() method doesn't access any state
that requires running it on the main actor.
So these aren't marked with @MainActor.
在上面版本的 PhotoGallery 中,drawUI() 方法在屏幕上绘制图库的图片,所以它需要隔离到主 actor。photoNames 属性不直接创建 UI,但它确实存储了 drawUI() 函数用于绘制 UI 的状态,因此该属性也需要仅在主 actor 上访问。相反,对 hasCachedPhotos 属性的更改不与 UI 交互,cachePhotos() 方法不访问任何需要在主 actor 上运行的状态。所以这些没有标记 @MainActor。
As with the earlier examples,
if you're using a framework to build your UI,
the property wrappers from that framework
probably already mark your UI state properties as @MainActor.
When defining a property wrapper,
if its wrappedValue property is marked @MainActor,
then any property you apply that property wrapper to
is also implicitly marked @MainActor.
与前面的例子一样,如果你使用框架来构建 UI,该框架的属性包装器可能已经将你的 UI 状态属性标记为 @MainActor。在定义属性包装器时,如果其 wrappedValue 属性标记为 @MainActor,那么你应用该属性包装器的任何属性也会隐式地标记为 @MainActor。
Actors
Swift provides the main actor for you --- you can also define your own actors. Actors let you safely share information between concurrent code.
Swift 为你提供了主 actor——你也可以定义自己的 actor。Actor 让你可以在并发代码之间安全地共享信息。
Like classes, actors are reference types, so the comparison of value types and reference types in Classes Are Reference Types applies to actors as well as classes. 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. For example, here's an actor that records temperatures:
就和类一样,actor 也是引用类型,所以在 类是引用类型 一文中有关引用类型和值类型的对比,同时适用于类和 actor。与类不同的是,actor 在同一时刻只允许一项任务访问其可变状态,这样多个任务同时与 actor 交互时才不会产生安全性问题。举个例子,下面是一个用于记录温度的 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
}
}You introduce an actor with the actor keyword,
followed by its definition in a pair of braces.
The TemperatureLogger actor has properties
that other code outside the actor can access,
and restricts the max property so only code inside the actor
can update the maximum value.
你可通过 actor 关键字和紧随其后的括弧来定义一个 actor。TemperatureLogger actor 具有可供外部代码访问的属性,也有 max 这个只有 actor 内部代码才能修改的属性。
You create an instance of an actor
using the same initializer syntax as structures and classes.
When you access a property or method of an actor,
you use await to mark the potential suspension point.
For example:
你可通过使用与结构体和类相同的构造体语法来创建一个 actor 实例。在你访问一个 actor 的属性或方法时,需要使用 await 来表明这是一个潜在的挂起点。比如:
let logger = TemperatureLogger(label: "Outdoors", measurement: 25)
print(await logger.max)
// Prints "25".In this example,
accessing logger.max is a possible suspension point.
Because the actor allows only one task at a time to access its mutable state,
if code from another task is already interacting with the logger,
this code suspends while it waits to access the property.
在这个例子中,对 logger.max 的访问是一个可能的挂起点。这是因为其 actor 同一时刻只允许一项任务访问其可变状态。如果另一项任务正与 logger 进行交互,这段代码就需要先挂起,直到轮到他来访问这个属性。
In contrast,
code that's part of the actor doesn't write await
when accessing the actor's properties.
For example,
here's a method that updates a TemperatureLogger with a new temperature:
相比之下,actor 内部的代码不需要使用 await 来访问 actor 的属性。比如,这是一个用于更新 TemperatureLogger 所记录温度的方法:
extension TemperatureLogger {
func update(with measurement: Int) {
measurements.append(measurement)
if measurement > max {
max = measurement
}
}
}The update(with:) method is already running on the actor,
so it doesn't mark its access to properties like max with await.
This method also shows one of the reasons
why actors allow only one task at a time to interact with their mutable state:
Some updates to an actor's state temporarily break invariants.
The TemperatureLogger actor keeps track of
a list of temperatures and a maximum temperature,
and it updates the maximum temperature when you record a new measurement.
In the middle of an update,
after appending the new measurement but before updating max,
the temperature logger is in a temporary inconsistent state.
Preventing multiple tasks from interacting with the same instance simultaneously
prevents problems like the following sequence of events:
update(with:) 这个方法已经是在 actor 上运行的了,所以它在访问 max 这样的属性时,不需要使用 await 来进行标注。这个方法也揭示了 actor 同一时刻仅允许一项任务与其可变状态交互的其中一项原因:有些对于 actor 状态的更新会暂时打破不变式。TemperatureLogger 这个 actor 记录了一系列温度数据以及一项最高温度,并且它应当会在记录一项新的测量数据时,更新最高温度纪录。在一次更新操作插入新的测量数据之后、更新最高温度纪录之前的那一刻,我们的温度记录器 actor 暂时处于一个非法的状态中。禁止多个任务同时与某个实例交互能够在下列事件序列中,防止问题的出现:
- Your code calls the
update(with:)method. It updates themeasurementsarray first. - Before your code can update
max, code elsewhere reads the maximum value and the array of temperatures. - Your code finishes its update by changing
max.
- 你的代码调用
update(with:)方法,该方法先更新了measurements数组。 - 在你的代码能够更新
max之前,其他地方的代码读取了最大温度值和温度数据列表。 - 然后,你的代码才更新了
max数据,完成了整个更新流程。
In this case,
the code running elsewhere would read incorrect information
because its access to the actor was interleaved
in the middle of the call to update(with:)
while the data was temporarily invalid.
You can prevent this problem when using Swift actors
because they only allow one operation on their state at a time,
and because that code can be interrupted
only in places where await marks a suspension point.
Because update(with:) doesn't contain any suspension points,
no other code can access the data in the middle of an update.
在这种情况下,其它地方的代码会读取到错误的信息,因为他们对 actor 的访问被插入在了 update(with:) 执行过程的中间,从而读取到了不合法的数据。使用 Swift actor 能让你避免这种情况,因为它同一时刻只允许一项对其状态的操作,且代码执行只能在有 await 标注的挂起点处被打断;又因为 update(with:) 并不包含任何挂起点,其执行过程中没有任何其它代码可以访问数据。
If code outside the actor tries to access those properties directly, like accessing a structure or class's properties, you'll get a compile-time error. For example:
如果 actor 之外的代码尝试直接访问这些属性,编译器会报错。比如:
print(logger.max) // ErrorAccessing logger.max without writing await fails because
the properties of an actor are part of that actor's isolated local state.
The code to access this property needs to run as part of the actor,
which is an asynchronous operation and requires writing await.
Swift guarantees that
only code running on an actor can access that actor's local state.
This guarantee is known as actor isolation.
不加 await 访问 logger.max 会失败,因为一个 actor 的属性是这个 actor 的本地受隔离状态的一部分。想要访问该属性的代码必须在此 actor 上执行,这是一个异步操作,所以必须用 await 标注。Swift 保证了只有在 actor 上运行的代码才能访问这个 actor 的本地状态。这种保证称为 actor 隔离。
The following aspects of the Swift concurrency model work together to make it easier to reason about shared mutable state:
Swift 并发模型的以下几个特点共同降低了使用者对共享可变属性的理解成本:
- Code in between possible suspension points runs sequentially, without the possibility of interruption from other concurrent code. However, multiple pieces of concurrent code can run at the same time, so other code could be running simultaneously.
- 挂起点之间的代码总是按顺序执行,且不可能被任何其它并发代码打断。
- Code that interacts with an actor's local state runs only on that actor.
- 与一个 actor 本地状态交互的代码只会运行在这个 actor 之上。
- An actor runs only one piece of code at a time.
- 一个 actor 一次只运行一段代码。
Because of these guarantees,
code that doesn't include await and that's inside an actor
can make the updates without a risk of other places in your program
observing the temporarily invalid state.
For example,
the code below converts measured temperatures from Fahrenheit to Celsius:
基于这些保证,处于一个 actor 之内、且不包含 await 的方法可以安全地对 actor 状态进行更新,而不用担心程序中的其它部分意外读取到不合法状态。
extension TemperatureLogger {
func convertFahrenheitToCelsius() {
for i in measurements.indices {
measurements[i] = (measurements[i] - 32) * 5 / 9
}
}
}The code above converts the array of measurements, one at a time.
While the map operation is in progress,
some temperatures are in Fahrenheit and others are in Celsius.
However, because none of the code includes await,
there are no potential suspension points in this method.
The state that this method modifies belongs to the actor,
which protects it against code reading or modifying it
except when that code runs on the actor.
This means there's no way for other code
to read a list of partially converted temperatures
while unit conversion is in progress.
上面这段代码会逐个转换数组内的测量数据。在 map 操作的执行过程中,有些温度还是华氏度,有些则已经转换为了摄氏度。但是,因为其中没有任何代码包含 await,这里不会出现潜在的挂起点。这个方法所修改的状态从属于 actor,actor 为这个状态提供了保护,使其免受不在 actor 上运行的代码的读取或修改。这意味着其它代码不可能有办法读取到单位转换过程中,只被转换了一半的测量数据。
In addition to writing code in an actor
that protects temporary invalid state by omitting potential suspension points,
you can move that code into a synchronous method.
The convertFahrenheitToCelsius() method above is a synchronous method,
so it's guaranteed to never contain potential suspension points.
This function encapsulates the code
that temporarily makes the data model inconsistent,
and makes it easier for anyone reading the code
to recognize that no other code can run
before data consistency is restored by completing the work.
It's important that Swift doesn't switch from this code
to run code from another part of the program
during that period of time.
In the future,
if you try to add concurrent code to this function,
introducing a possible suspension point,
you'll get a compile-time error instead of introducing a bug.
除了将代码编写在一个 actor 中,并在其中舍弃掉所有的挂起点之外,还有更进一步的方式来避免出现临时性的不合法状态:将这些代码移动到一个同步方法中。上方的 convertFahrenheitToCelsius() 方法就是一个同步方法,保证了它永远不可能包含挂起点。这个方法封装了会暂时造成不合法数据状态的代码,从而使得阅读代码的人更容易意识到:在这个方法完成自己的任务、并将合法的数据状态被恢复之前,没有其它代码可以运行。在未来,如果你试图向这个方法中添加并发代码,或是一个可能的挂起点,编译器会及时报错,以防引入新 bug。
Global Actors 全局 Actor
The main actor is a global singleton instance of the MainActor type.
An actor can normally have multiple instances,
each of which provides independent isolation.
This is why you declare all of an actor's isolated data
as instance properties of that actor.
However, because MainActor is a singleton ---
there is only ever a single instance of this type ---
the type alone is sufficient to identify the actor,
allowing you to mark main-actor isolation using just an attribute.
This approach gives you more flexibility to organize your code
in the way that works best for you.
主 actor 是 MainActor 类型的全局单例实例。Actor 通常可以有多个实例,每个实例提供独立的隔离。这就是为什么你将 actor 的所有隔离数据声明为该 actor 的实例属性。然而,因为 MainActor 是单例——该类型只有一个实例——仅类型本身就足以标识该 actor,允许你仅使用属性来标记主 actor 隔离。这种方法让你更灵活地以最适合你的方式组织代码。
You can define your own singleton global actors
using the @globalActor attribute,
as described in globalActor.
你可以使用 @globalActor 属性定义自己的单例全局 actor,如 globalActor 中所述。
Sendable Types 可发送类型
Tasks and actors let you divide a program into pieces that can safely run concurrently. Inside of a task or an instance of an actor, the part of a program that contains mutable state, like variables and properties, is called a concurrency domain. Some kinds of data can't be shared between concurrency domains, because that data contains mutable state, but it doesn't protect against overlapping access.
任务和 actor 能让你将一个程序分成多个小段并安全地并行运行。一个任务或是一个 actor 的实例内部所包含的可变状态(例如变量或属性),被称为并发域。有些数据无法在不同的并发域之间共享,因为这些数据包含可变状态,但其又无法对重叠访问提供保护。
A type that can be shared from one concurrency domain to another is known as a sendable type. For example, it can be passed as an argument when calling an actor method or be returned as the result of a task. The examples earlier in this chapter didn't discuss sendability because those examples use simple value types that are always safe to share for the data being passed between concurrency domains. In contrast, some types aren't safe to pass across concurrency domains. For example, a class that contains mutable properties and doesn't serialize access to those properties can produce unpredictable and incorrect results when you pass instances of that class between different tasks.
对于可以被从一个并发域共享到另一个并发域的类型,被称作可发送类型。例如,它可以在调用一个 actor 时被作为参数传递,或是作为一项任务的返回值返回。本章前述的几个例子没有讨论可发送性,因为这些例子使用的都是简单的值类型,而这些类型永远是可以被安全地在并发域之前传递的。相比之下,有些类型无法被安全地在并发域之间传递。比如,一个包含了可变属性、但又没有添加串行访问保护的类,如果在不同任务之间传递,可能会产生无法预测或是错误的结果。
You mark a type as being sendable
by declaring conformance to the Sendable protocol.
That protocol doesn't have any code requirements,
but it does have semantic requirements that Swift enforces.
In general, there are three ways for a type to be sendable:
你可以通过使一个类型遵循 Sendable 协议来将其标注为可发送的。这个协议并不包含任何代码要求,但是其包含了由 Swift 强制实施的语义要求。总的来说,有三种方式能让一个类变得可发送:
- The type is a value type, and its mutable state is made up of other sendable data --- for example, a structure with stored properties that are sendable or an enumeration with associated values that are sendable.
- The type doesn't have any mutable state, and its immutable state is made up of other sendable data --- for example, a structure or class that has only read-only properties.
- The type has code that ensures the safety of its mutable state,
like a class that's marked
@MainActoror a class that serializes access to its properties on a particular thread or queue.
- 这个类型是一个值类型,并且它的可变状态仅由其它的可发送数据构成 —— 比如,一个只包含可发送属性的结构体,或是一个只包含可发送关联值的枚举。
- 这个类型不包含任何可变状态,并且它的不可变状态只由其它的可发送数据构成 —— 比如,一个仅包含只读属性的结构体或类。
- 这个类型包含能够保证其可变属性访问安全性的代码,比如一个被标注了
@MainActor的类,或是一个通过队列 / 线程来对其属性增加了串行访问保护的类。
For a detailed list of the semantic requirements,
see the Sendable protocol reference.
若想了解所有的语义要求,请参见 Sendable 协议指南。
Some types are always sendable, like structures that have only sendable properties and enumerations that have only sendable associated values. For example:
有些类型总是可发送的,比如只包含可发送属性的结构体,或是只包含可发送关联值的枚举。比如:
struct TemperatureReading: Sendable {
var measurement: Int
}
extension TemperatureLogger {
func addReading(from reading: TemperatureReading) {
measurements.append(reading.measurement)
}
}
let logger = TemperatureLogger(label: "Tea kettle", measurement: 85)
let reading = TemperatureReading(measurement: 45)
await logger.addReading(from: reading)Because TemperatureReading is a structure that has only sendable properties,
and the structure isn't marked public or @usableFromInline,
it's implicitly sendable.
Here's a version of the structure
where conformance to the Sendable protocol is implied:
由于 TemperatureReading 是个结构体,并且只包含可发送属性,又因为这个结构体没有被标注为 public 或 @usableFromInline,它是隐式可发送的。下面这个版本的结构体隐式地遵从了 Sendable 协议:
struct TemperatureReading {
var measurement: Int
}To explicitly mark a type as not being sendable,
write an unavailable conformance to Sendable:
要显式地标注一个类型为不可发送,请编写一个不可用的 Sendable 遵循:
struct FileDescriptor {
let rawValue: Int
}
@available(*, unavailable)
extension FileDescriptor: Sendable {}You can also use an unavailable conformance to suppress implicit conformance to a protocol, as discussed in Implicit Conformance to a Protocol.
你还可以使用不可用的遵循来抑制对协议的隐式遵循,如 对协议的隐式遵循 中所述。