x-i18n: generated_at: “2026-03-01T14:38:55Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 84d2e46991bce433f8d50c29479e36fd0c7f62e735758c8a096ab4e1ebe58fe7 source_path: ch16-01-threads.md workflow: 16
使用线程同时运行代码 (Using Threads to Run Code Simultaneously)
Using Threads to Run Code Simultaneously
在大多数当前的操作系统中,执行程序的代码运行在“进程 (process)”中,操作系统将同时管理多个进程。在程序内部,你也可以拥有同时运行的独立部分。运行这些独立部分的功能被称为“线程 (threads)”。例如,一个 Web 服务器可以拥有多个线程,以便它能同时响应多个请求。
In most current operating systems, executed program’s code is run in a process, and the operating system will manage multiple processes at once. Within a program, you can also have independent parts that run simultaneously. The features that run these independent parts are called threads. For example, a web server could have multiple threads so that it can respond to more than one request at the same time.
将程序中的计算拆分为多个线程以同时运行多个任务可以提高性能,但也增加了复杂性。因为线程可以同时运行,所以无法固有地保证不同线程上代码部分的运行顺序。这可能导致一些问题,例如:
- 竞态条件 (Race conditions),其中线程以不一致的顺序访问数据或资源
- 死锁 (Deadlocks),其中两个线程互相等待,导致两个线程都无法继续
- 仅在某些情况下发生的 bug,且很难可靠地重现和修复
Splitting the computation in your program into multiple threads to run multiple tasks at the same time can improve performance, but it also adds complexity. Because threads can run simultaneously, there’s no inherent guarantee about the order in which parts of your code on different threads will run. This can lead to problems, such as:
- Race conditions, in which threads are accessing data or resources in an inconsistent order
- Deadlocks, in which two threads are waiting for each other, preventing both threads from continuing
- Bugs that only happen in certain situations and are hard to reproduce and fix reliably
Rust 试图减轻使用线程的负面影响,但在多线程上下文中编程仍然需要深思熟虑,并需要一种与单线程运行程序不同的代码结构。
Rust attempts to mitigate the negative effects of using threads, but programming in a multithreaded context still takes careful thought and requires a code structure that is different from that in programs running in a single thread.
编程语言实现线程的方式有几种,许多操作系统提供了编程语言可以调用以创建新线程的 API。Rust 标准库使用线程实现的“1:1”模型,即程序每个语言线程使用一个操作系统线程。有一些 crate 实现了其他线程模型,这些模型对 1:1 模型做出了不同的权衡。(Rust 的异步系统将在下一章介绍,它也提供了另一种并发方法。)
Programming languages implement threads in a few different ways, and many operating systems provide an API the programming language can call for creating new threads. The Rust standard library uses a 1:1 model of thread implementation, whereby a program uses one operating system thread per one language thread. There are crates that implement other models of threading that make different trade-offs to the 1:1 model. (Rust’s async system, which we will see in the next chapter, provides another approach to concurrency as well.)
使用 spawn 创建新线程 (Creating a New Thread with spawn)
Creating a New Thread with spawn
要创建一个新线程,我们调用 thread::spawn 函数并传递给它一个闭包(我们在第 13 章讨论过闭包),该闭包包含我们想要在新线程中运行的代码。示例 16-1 中的示例从主线程打印一些文本,并从新线程打印其他文本。
To create a new thread, we call the thread::spawn function and pass it a
closure (we talked about closures in Chapter 13) containing the code we want to
run in the new thread. The example in Listing 16-1 prints some text from a main
thread and other text from a new thread.
#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch16-fearless-concurrency/listing-16-01/src/main.rs}}
}
注意,当 Rust 程序的主线程完成时,所有生成的线程都会被关闭,无论它们是否已完成运行。该程序的输出每次可能会略有不同,但看起来类似于以下内容:
Note that when the main thread of a Rust program completes, all spawned threads are shut down, whether or not they have finished running. The output from this program might be a little different every time, but it will look similar to the following:
hi number 1 from the main thread!
hi number 1 from the spawned thread!
hi number 2 from the main thread!
hi number 2 from the spawned thread!
hi number 3 from the main thread!
hi number 3 from the spawned thread!
hi number 4 from the main thread!
hi number 4 from the spawned thread!
hi number 5 from the spawned thread!
对 thread::sleep 的调用强制线程在短时间内停止执行,允许另一个线程运行。线程可能会轮流运行,但这并不能保证:这取决于你的操作系统如何调度线程。在这次运行中,尽管来自生成线程的打印语句在代码中首先出现,但主线程首先打印了。尽管我们告诉生成线程打印到 i 等于 9 为止,但在主线程关闭之前它只执行到了 5 。
The calls to thread::sleep force a thread to stop its execution for a short
duration, allowing a different thread to run. The threads will probably take
turns, but that isn’t guaranteed: It depends on how your operating system
schedules the threads. In this run, the main thread printed first, even though
the print statement from the spawned thread appears first in the code. And even
though we told the spawned thread to print until i is 9, it only got to 5
before the main thread shut down.
如果你运行此代码并且只看到主线程的输出,或者没有看到任何重叠,请尝试增加范围内的数字,以为操作系统提供更多在线程之间切换的机会。
If you run this code and only see output from the main thread, or don’t see any overlap, try increasing the numbers in the ranges to create more opportunities for the operating system to switch between the threads.
等待所有线程完成 (Waiting for All Threads to Finish)
Waiting for All Threads to Finish
示例 16-1 中的代码不仅大多数时候由于主线程结束而提前停止了生成的线程,而且由于无法保证线程运行的顺序,我们也无法保证生成的线程根本会有机会运行!
The code in Listing 16-1 not only stops the spawned thread prematurely most of the time due to the main thread ending, but because there is no guarantee on the order in which threads run, we also can’t guarantee that the spawned thread will get to run at all!
我们可以通过将 thread::spawn 的返回值保存在一个变量中来解决生成的线程未运行或提前结束的问题。 thread::spawn 的返回类型是 JoinHandle<T> 。 JoinHandle<T> 是一个拥有所有权的值,当我们对其调用 join 方法时,它将等待其线程完成。示例 16-2 展示了如何使用我们在示例 16-1 中创建的线程的 JoinHandle<T> ,以及如何调用 join 以确保生成的线程在 main 退出之前完成。
We can fix the problem of the spawned thread not running or of it ending
prematurely by saving the return value of thread::spawn in a variable. The
return type of thread::spawn is JoinHandle<T>. A JoinHandle<T> is an
owned value that, when we call the join method on it, will wait for its
thread to finish. Listing 16-2 shows how to use the JoinHandle<T> of the
thread we created in Listing 16-1 and how to call join to make sure the
spawned thread finishes before main exits.
#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch16-fearless-concurrency/listing-16-02/src/main.rs}}
}
在句柄上调用 join 会阻塞当前正在运行的线程,直到由该句柄代表的线程终止。“阻塞 (Blocking)”一个线程意味着该线程被阻止执行工作或退出。因为我们将 join 的调用放在了主线程的 for 循环之后,运行示例 16-2 应该产生类似于以下内容的输出:
Calling join on the handle blocks the thread currently running until the
thread represented by the handle terminates. Blocking a thread means that
thread is prevented from performing work or exiting. Because we’ve put the call
to join after the main thread’s for loop, running Listing 16-2 should
produce output similar to this:
hi number 1 from the main thread!
hi number 2 from the main thread!
hi number 1 from the spawned thread!
hi number 3 from the main thread!
hi number 2 from the spawned thread!
hi number 4 from the main thread!
hi number 3 from the spawned thread!
hi number 4 from the spawned thread!
hi number 5 from the spawned thread!
hi number 6 from the spawned thread!
hi number 7 from the spawned thread!
hi number 8 from the spawned thread!
hi number 9 from the spawned thread!
这两个线程继续交替运行,但由于调用了 handle.join() ,主线程在等待,直到生成的线程完成后才结束。
The two threads continue alternating, but the main thread waits because of the
call to handle.join() and does not end until the spawned thread is finished.
但让我们看看如果我们改为将 handle.join() 移动到 main 中的 for 循环“之前”,会发生什么,如下所示:
But let’s see what happens when we instead move handle.join() before the
for loop in main, like this:
#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch16-fearless-concurrency/no-listing-01-join-too-early/src/main.rs}}
}
主线程将等待生成的线程完成,然后运行它的 for 循环,因此输出将不再交错,如下所示:
The main thread will wait for the spawned thread to finish and then run its
for loop, so the output won’t be interleaved anymore, as shown here:
hi number 1 from the spawned thread!
hi number 2 from the spawned thread!
hi number 3 from the spawned thread!
hi number 4 from the spawned thread!
hi number 5 from the spawned thread!
hi number 6 from the spawned thread!
hi number 7 from the spawned thread!
hi number 8 from the spawned thread!
hi number 9 from the spawned thread!
hi number 1 from the main thread!
hi number 2 from the main thread!
hi number 3 from the main thread!
hi number 4 from the main thread!
一些细微的细节,比如 join 在哪里被调用,都会影响你的线程是否在同一时间运行。
Small details, such as where join is called, can affect whether or not your
threads run at the same time.
在线程中使用 move 闭包 (Using move Closures with Threads)
Using move Closures with Threads
我们经常会为传递给 thread::spawn 的闭包使用 move 关键字,因为这样闭包就会获取它从环境中使用的值的所有权,从而将这些值的所有权从一个线程转移到另一个线程。在第 13 章的“捕获引用或移动所有权”中,我们讨论了闭包背景下的 move 。现在我们将更多地关注 move 和 thread::spawn 之间的交互。
We’ll often use the move keyword with closures passed to thread::spawn
because the closure will then take ownership of the values it uses from the
environment, thus transferring ownership of those values from one thread to
another. In “Capturing References or Moving Ownership” in Chapter 13, we discussed move in the context of closures. Now we’ll
concentrate more on the interaction between move and thread::spawn.
注意在示例 16-1 中,我们传递给 thread::spawn 的闭包不接收任何参数:我们在生成的线程代码中没有使用来自主线程的任何数据。要在生成的线程中使用来自主线程的数据,生成的线程闭包必须捕获它所需的值。示例 16-3 展示了一次在主线程中创建一个向量并在生成的线程中使用它的尝试。然而,正如你很快就会看到的,这目前还行不通。
Notice in Listing 16-1 that the closure we pass to thread::spawn takes no
arguments: We’re not using any data from the main thread in the spawned
thread’s code. To use data from the main thread in the spawned thread, the
spawned thread’s closure must capture the values it needs. Listing 16-3 shows
an attempt to create a vector in the main thread and use it in the spawned
thread. However, this won’t work yet, as you’ll see in a moment.
{{#rustdoc_include ../listings/ch16-fearless-concurrency/listing-16-03/src/main.rs}}
该闭包使用了 v ,因此它将捕获 v 并使其成为闭包环境的一部分。因为 thread::spawn 在一个新线程中运行此闭包,所以我们应该能够在那个新线程中访问 v 。但当我们编译这个例子时,我们得到了以下错误:
The closure uses v, so it will capture v and make it part of the closure’s
environment. Because thread::spawn runs this closure in a new thread, we
should be able to access v inside that new thread. But when we compile this
example, we get the following error:
{{#include ../listings/ch16-fearless-concurrency/listing-16-03/output.txt}}
Rust “推断” 如何捕获 v ,并且因为 println! 只需要一个 v 的引用,闭包尝试借用 v 。然而,有一个问题:Rust 无法判断生成的线程将运行多久,因此它不知道 v 的引用是否始终有效。
Rust infers how to capture v, and because println! only needs a reference
to v, the closure tries to borrow v. However, there’s a problem: Rust can’t
tell how long the spawned thread will run, so it doesn’t know whether the
reference to v will always be valid.
示例 16-4 提供了一个更有可能导致 v 的引用无效的场景。
Listing 16-4 provides a scenario that’s more likely to have a reference to v
that won’t be valid.
{{#rustdoc_include ../listings/ch16-fearless-concurrency/listing-16-04/src/main.rs}}
如果 Rust 允许我们运行这段代码,则有一种可能性是生成的线程会立即被放到后台而根本没有运行。生成的线程内部有一个对 v 的引用,但主线程立即使用我们在第 15 章讨论过的 drop 函数丢弃了 v 。然后,当生成的线程开始执行时, v 就不再有效了,因此对它的引用也是无效的。噢不!
If Rust allowed us to run this code, there’s a possibility that the spawned
thread would be immediately put in the background without running at all. The
spawned thread has a reference to v inside, but the main thread immediately
drops v, using the drop function we discussed in Chapter 15. Then, when the
spawned thread starts to execute, v is no longer valid, so a reference to it
is also invalid. Oh no!
要修复示例 16-3 中的编译器错误,我们可以使用错误消息的建议:
To fix the compiler error in Listing 16-3, we can use the error message’s advice:
help: to force the closure to take ownership of `v` (and any other referenced variables), use the `move` keyword
|
6 | let handle = thread::spawn(move || {
| ++++
(帮助:要强制闭包获取 v(以及任何其他被引用的变量)的所有权,请使用 move 关键字)
通过在闭包前添加 move 关键字,我们强制闭包获取它所使用值的所有权,而不是允许 Rust 推断它应该借用这些值。对示例 16-3 进行修改后的示例 16-5 将按我们的意图编译并运行。
By adding the move keyword before the closure, we force the closure to take
ownership of the values it’s using rather than allowing Rust to infer that it
should borrow the values. The modification to Listing 16-3 shown in Listing
16-5 will compile and run as we intend.
#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch16-fearless-concurrency/listing-16-05/src/main.rs}}
}
我们可能想尝试同样的事情来修复示例 16-4 中主线程通过使用 move 闭包调用 drop 的代码。然而,这一修复将行不通,因为示例 16-4 尝试做的操作由于另一个原因被禁止了。如果我们向闭包添加 move ,我们会将 v 移动到闭包的环境中,我们就不再能在主线程中对其调用 drop 了。我们会得到如下编译错误:
We might be tempted to try the same thing to fix the code in Listing 16-4 where
the main thread called drop by using a move closure. However, this fix will
not work because what Listing 16-4 is trying to do is disallowed for a
different reason. If we added move to the closure, we would move v into the
closure’s environment, and we could no longer call drop on it in the main
thread. We would get this compiler error instead:
{{#include ../listings/ch16-fearless-concurrency/output-only-01-move-drop/output.txt}}
Rust 的所有权规则再次救了我们!我们从示例 16-3 的代码中得到了一个错误,是因为 Rust 是保守的,仅为线程借用 v ,这意味着主线程理论上可以使生成的线程的引用无效。通过告诉 Rust 将 v 的所有权移动到生成的线程,我们就向 Rust 保证了主线程将不再使用 v 。如果我们以相同的方式更改示例 16-4,那么当我们尝试在主线程中使用 v 时就会违反所有权规则。 move 关键字覆盖了 Rust 保守的默认借用行为;它不代表我们可以违反所有权规则。
Rust’s ownership rules have saved us again! We got an error from the code in
Listing 16-3 because Rust was being conservative and only borrowing v for the
thread, which meant the main thread could theoretically invalidate the spawned
thread’s reference. By telling Rust to move ownership of v to the spawned
thread, we’re guaranteeing to Rust that the main thread won’t use v anymore.
If we change Listing 16-4 in the same way, we’re then violating the ownership
rules when we try to use v in the main thread. The move keyword overrides
Rust’s conservative default of borrowing; it doesn’t let us violate the
ownership rules.
既然我们已经介绍了线程是什么以及线程 API 提供的方法,让我们来看看一些可以使用线程的情况。
Now that we’ve covered what threads are and the methods supplied by the thread API, let’s look at some situations in which we can use threads.