# 執行緒

執行緒（thread）讓程式同時做好幾件事；本頁說明怎麼開執行緒、怎麼把資料交給它，以及 Rust 如何在編譯期就擋下並行錯誤。

## 為什麼需要執行緒

一個程式啟動時只有一條「主執行緒」，所有程式碼依序執行。現在的 CPU 有多個核心，如果工作可以拆開（例如算兩段範圍的質數、同時處理多個檔案），就能開更多執行緒，讓多個核心一起做。

| 名詞 | 意思 |
| --- | --- |
| 並行（concurrency） | 多個工作在同一段時間內都有進展 |
| 平行（parallelism） | 多個工作真的在不同核心上同時執行 |
| 資料競爭（data race） | 兩個執行緒同時存取同一份資料，且至少一個在寫，結果無法預測 |

Rust 標準庫的 `std::thread` 建立的是作業系統執行緒，每條都有自己的堆疊，由作業系統排程。API 細節見 [std::thread](/pkg-thread)。

### spawn 與 join：把工作分給兩個執行緒

`thread::spawn` 接收一個[閉包](/closures-basics)，在新執行緒執行並立刻回傳 `JoinHandle`；主執行緒可以繼續做別的事。之後呼叫 `join()` 等那條執行緒結束，並取得閉包的回傳值。

注意：`main` 結束時整個程式就結束，還沒跑完的子執行緒會直接被終止，所以要等結果就一定要 `join`。子執行緒 panic 時，`join` 會回傳 `Err`，不會連帶讓主執行緒 panic。

範例：
```rust
use std::thread;

fn count_primes(from: u32, to: u32) -> usize {
    (from..to)
        .filter(|&n| n >= 2 && (2..n).take_while(|d| d * d <= n).all(|d| n % d != 0))
        .count()
}

fn main() {
    let first = thread::spawn(|| count_primes(0, 50_000));
    let second = thread::spawn(|| count_primes(50_000, 100_000));

    let a = first.join().unwrap();
    let b = second.join().unwrap();
    println!("前半 {a} 個、後半 {b} 個，共 {} 個質數", a + b);
}
```

輸出：
```text
前半 5133 個、後半 4459 個，共 9592 個質數
```

兩條執行緒誰先算完每次都可能不同，但因為等 `join` 之後才印，輸出永遠一樣。

## 把資料交給執行緒

### 編譯不過：子執行緒借用區域變數

`thread::spawn` 要求閉包是 `'static`：不能借用任何可能比執行緒先消失的東西。編譯器不知道子執行緒會跑多久，萬一 `main` 先結束、`names` 被釋放，子執行緒手上就是一個懸垂參考。下面這段無法編譯：

```rust
use std::thread;

fn main() {
    let names = vec!["Ann", "Bob"];
    let handle = thread::spawn(|| {
        println!("{:?}", names);
    });
    handle.join().unwrap();
}
```

輸出：
```text
error[E0373]: closure may outlive the current function, but it borrows `names`, which is owned by the current function
 --> err_d3.rs:5:32
  |
5 |     let handle = thread::spawn(|| {
  |                                ^^ may outlive borrowed value `names`
6 |         println!("{:?}", names);
  |                          ----- `names` is borrowed here
  |
help: to force the closure to take ownership of `names` (and any other referenced variables), use the `move` keyword
  |
5 |     let handle = thread::spawn(move || {
  |                                ++++
```

即使程式裡有 `join`，編譯器也不會因此放行；它只看型別上的保證。

### move 閉包：把所有權交給執行緒

加上 `move`，閉包取得 `names` 的所有權，資料跟著執行緒走，活多久都沒問題。代價是 `main` 之後不能再用 `names`；要拿回結果，就讓閉包回傳它，再從 `join` 取得。

範例：
```rust
use std::thread;

fn main() {
    let names = vec!["Ann", "Bob"];
    let handle = thread::spawn(move || {
        println!("子執行緒拿到：{:?}", names);
        names.len()
    });
    let n = handle.join().unwrap();
    println!("子執行緒回傳 {n} 個名字");
}
```

輸出：
```text
子執行緒拿到：["Ann", "Bob"]
子執行緒回傳 2 個名字
```

多條執行緒都要讀同一份資料時，`move` 一份給一條不夠用，這時改用 `Arc` 共享所有權，見[智慧指標](/smart-pointers-overview)與[共享狀態](/concurrency-shared-state)。

### scoped thread：保證先結束，就能借用

`thread::scope`（Rust 1.63 起）開一個作用域，裡面用 `s.spawn` 開的執行緒保證在 `scope` 回傳前全部結束。既然執行緒不會活得比區域變數久，閉包就可以直接借用，不必 `move` 也不必 `Arc`，原本的變數之後照常使用。

範例：
```rust
use std::thread;

fn main() {
    let numbers = vec![3, 1, 4, 1, 5, 9, 2, 6];
    let mut summary = String::new();

    thread::scope(|s| {
        let sum = s.spawn(|| numbers.iter().sum::<i32>());
        let max = s.spawn(|| *numbers.iter().max().unwrap());
        summary = format!("總和 {}、最大 {}", sum.join().unwrap(), max.join().unwrap());
    });

    println!("{summary}");
    println!("numbers 仍屬於 main：{:?}", numbers);
}
```

輸出：
```text
總和 31、最大 9
numbers 仍屬於 main：[3, 1, 4, 1, 5, 9, 2, 6]
```

## 無畏並行

其他語言裡，資料競爭往往要到正式環境、偶爾當機時才發現。Rust 把同一套[借用規則](/ownership-references)延伸到執行緒：「同時多個讀，或只有一個寫」在編譯期就檢查。能編譯的安全 Rust 程式不會有資料競爭，這就是「無畏並行（fearless concurrency）」：可以放心改寫並行程式，編譯器會把關。

注意：無畏並行保證沒有資料競爭，但不保證沒有死結或邏輯錯誤（例如鎖的順序錯了），見[共享狀態](/concurrency-shared-state)。

### 編譯不過：兩個執行緒同時修改同一個 Vec

兩條執行緒都想 `push` 到 `results`，等於同時存在兩個 `&mut`，違反「只有一個寫」。在 C 或 Go 裡這會編譯成功、執行時偶爾壞掉；在 Rust 這段無法編譯：

```rust
use std::thread;

fn main() {
    let mut results = Vec::new();
    thread::scope(|s| {
        s.spawn(|| results.push(1));
        s.spawn(|| results.push(2));
    });
    println!("{:?}", results);
}
```

輸出：
```text
error[E0499]: cannot borrow `results` as mutable more than once at a time
   --> err_d6.rs:7:17
    |
  5 |     thread::scope(|s| {
    |                    - has type `&'1 Scope<'1, '_>`
  6 |         s.spawn(|| results.push(1));
    |         ---------------------------
    |         |       |  |
    |         |       |  first borrow occurs due to use of `results` in closure
    |         |       first mutable borrow occurs here
    |         argument requires that `results` is borrowed for `'1`
  7 |         s.spawn(|| results.push(2));
    |                 ^^ ------- second borrow occurs due to use of `results` in closure
    |                 |
    |                 second mutable borrow occurs here
```

修法有三種：讓每條執行緒回傳自己的結果再由 `join` 收集；用[訊息傳遞](/concurrency-channels)把結果送回來；或用 `Mutex` 保護共享的 `Vec`（見[共享狀態](/concurrency-shared-state)）。

### 正確作法：把資料切成互不重疊的區塊

如果每條執行緒只碰自己那一段，就不需要任何鎖。`chunks_mut` 把切片分成互不重疊的 `&mut [T]`，編譯器知道它們不重疊，所以允許各自交給不同執行緒修改（切片見[切片型別](/ownership-slices)）。

範例：
```rust
use std::thread;

fn main() {
    let mut pixels = vec![10u8, 20, 30, 40, 50, 60, 70, 80];

    thread::scope(|s| {
        for chunk in pixels.chunks_mut(3) {
            s.spawn(move || {
                for p in chunk.iter_mut() {
                    *p = 255 - *p;
                }
            });
        }
    });

    println!("{:?}", pixels);
}
```

輸出：
```text
[245, 235, 225, 215, 205, 195, 185, 175]
```

這裡的 `move` 搬進閉包的是 `chunk` 這個 `&mut [u8]`，不是整個 `pixels`。

## 重點整理

- `thread::spawn` 開執行緒、`join` 等它結束並取回值；`main` 結束時程式就結束
- `spawn` 的閉包必須是 `'static`，借用區域變數會得到 E0373，用 `move` 交出所有權
- `thread::scope`（Rust 1.63 起）保證執行緒先結束，因此可以直接借用
- 借用規則延伸到執行緒，資料競爭在編譯期就被擋下
- 能切開的資料就切開各自處理，最不需要同步

## 資料來源

- [The Rust Programming Language（章節架構參考）](https://doc.rust-lang.org/book/)
- [The Rust Reference](https://doc.rust-lang.org/reference/)
- [Rust 標準庫文件](https://doc.rust-lang.org/std/)
- [Rust 官方部落格](https://blog.rust-lang.org/)
