# std::thread

建立與管理作業系統執行緒（thread），讓多段程式碼同時執行。

## 這個模組做什麼

執行緒是程式裡可以獨立執行的工作線。一個程式啟動時只有主執行緒；當你想同時做多件事（例如同時處理多個檔案、讓計算吃滿多核心 CPU），就用 `std::thread` 再開新的執行緒。

| 需求 | 用法 |
| --- | --- |
| 開一個背景工作，之後取回結果 | `thread::spawn` + `JoinHandle::join` |
| 子執行緒要借用區域變數 | `thread::scope` |
| 指定名稱或堆疊大小 | `thread::Builder` |
| 暫停目前執行緒 | `thread::sleep` |
| 查詢可用核心數 | `thread::available_parallelism` |
| 每個執行緒各自一份的變數 | `thread_local!` |

Rust 在編譯期就檢查資料能否安全地跨執行緒：送進去的值必須是 `Send`，共享的值必須是 `Sync`（見 [std::marker](/pkg-marker)）。執行緒之間要共享可變資料用 [std::sync](/pkg-sync)，要傳訊息用 [std::sync::mpsc](/pkg-sync-mpsc)。

注意：多個執行緒的執行順序由作業系統決定，每次執行都可能不同。要得到確定的結果，就等 `join` 之後再依序處理。

## 匯入

```rust
use std::thread;
use std::time::Duration;
```

## 常用 API

### spawn 與 join：開執行緒並等它結束

`thread::spawn` 接收一個閉包，在新執行緒執行，立刻回傳 `JoinHandle<T>`。呼叫 `join()` 會等待該執行緒結束並取得閉包的回傳值。如果不 `join`，主執行緒結束時程式就會結束，子執行緒可能還沒跑完。

簽名：
```rust
pub fn spawn<F, T>(f: F) -> JoinHandle<T>
where
    F: FnOnce() -> T + Send + 'static,
    T: Send + 'static,
impl<T> JoinHandle<T> {
    pub fn join(self) -> Result<T>
}
```

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

fn main() {
    let handles: Vec<_> = (1..=4)
        .map(|i| thread::spawn(move || i * i))
        .collect();
    let results: Vec<i32> = handles.into_iter().map(|h| h.join().unwrap()).collect();
    println!("{:?}", results);
}
```

輸出：
```text
[1, 4, 9, 16]
```

雖然四個執行緒完成的先後不固定，但範例依建立順序 `join`，所以結果永遠是同樣的順序。

### move 閉包：把資料交給執行緒

`spawn` 要求閉包是 `'static`：子執行緒可能比目前函式活得更久，所以不能借用區域變數。加上 `move` 會把捕獲的變數所有權移進閉包。移走之後，原本的作用域就不能再使用那個變數。

簽名：
```rust
move || { ... }
```

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

fn main() {
    let words = vec![String::from("alpha"), String::from("beta")];
    let handle = thread::spawn(move || {
        words.iter().map(|w| w.to_uppercase()).collect::<Vec<_>>()
    });
    let upper = handle.join().unwrap();
    println!("{:?}", upper);
}
```

輸出：
```text
["ALPHA", "BETA"]
```

若拿掉 `move`，編譯器會報錯，說閉包可能比 `words` 活得久。

### join 回傳 Err：子執行緒 panic

子執行緒 panic 不會讓整個程式崩潰，而是讓 `join()` 回傳 `Err`，裡面是 panic 的內容（`Box<dyn Any + Send>`），可用 `downcast_ref` 讀出訊息，見 [std::any](/pkg-any)。

範例先用 `panic::set_hook` 換掉預設的 panic 輸出，避免訊息印到 stderr，方便閱讀。

簽名：
```rust
pub type Result<T> = core::result::Result<T, Box<dyn Any + Send + 'static>>;
```

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

fn main() {
    panic::set_hook(Box::new(|_| {}));
    let ok = thread::spawn(|| 10 / 2);
    let bad = thread::spawn(|| -> i32 { panic!("設定檔缺少欄位") });

    println!("ok = {:?}", ok.join());
    match bad.join() {
        Ok(v) => println!("bad = {v}"),
        Err(payload) => {
            let msg = payload.downcast_ref::<&str>().copied().unwrap_or("未知");
            println!("子執行緒 panic：{msg}");
        }
    }
}
```

輸出：
```text
ok = Ok(5)
子執行緒 panic：設定檔缺少欄位
```

### thread::scope：借用區域變數的執行緒

`thread::scope`（Rust 1.63 起）建立一個作用域，裡面用 `s.spawn` 開的執行緒保證在作用域結束前全部結束，因此可以直接借用外面的區域變數，不需要 `move` 或 `Arc`。作用域結束時會自動 join 尚未 join 的執行緒。

注意：如果作用域內有執行緒 panic 且沒有被你 `join` 處理，`thread::scope` 本身會在結束時 panic。

簽名：
```rust
pub fn scope<'env, F, T>(f: F) -> T
where
    F: for<'scope> FnOnce(&'scope Scope<'scope, 'env>) -> T,
```

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

fn main() {
    let scores = vec![72, 88, 95, 60, 79, 91];
    let mut report = String::new();

    let (max, avg) = thread::scope(|s| {
        let h1 = s.spawn(|| *scores.iter().max().unwrap());
        let h2 = s.spawn(|| scores.iter().sum::<i32>() as f64 / scores.len() as f64);
        s.spawn(|| report.push_str("統計完成"));
        (h1.join().unwrap(), h2.join().unwrap())
    });

    println!("最高 {max}，平均 {avg:.2}");
    println!("{report}");
}
```

輸出：
```text
最高 95，平均 80.83
統計完成
```

第三個執行緒以可變借用修改 `report`，前兩個則共享 `scores` 的不可變借用，借用規則照樣由編譯器檢查。

### Builder：命名與設定堆疊大小

`thread::Builder` 可以在開執行緒前設定名稱（出現在 panic 訊息與除錯工具中）與堆疊大小。和 `spawn` 不同，`Builder::spawn` 回傳 `io::Result`，作業系統無法建立執行緒時會得到 `Err` 而不是 panic。

簽名：
```rust
impl Builder {
    pub fn new() -> Builder
    pub fn name(self, name: String) -> Builder
    pub fn stack_size(self, size: usize) -> Builder
    pub fn spawn<F, T>(self, f: F) -> io::Result<JoinHandle<T>>
}
```

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

fn main() -> std::io::Result<()> {
    let handle = thread::Builder::new()
        .name(String::from("worker-1"))
        .stack_size(64 * 1024)
        .spawn(|| {
            let me = thread::current();
            format!("我是 {}", me.name().unwrap_or("無名"))
        })?;
    println!("{}", handle.join().unwrap());
    println!("主執行緒名稱：{:?}", thread::current().name());
    Ok(())
}
```

輸出：
```text
我是 worker-1
主執行緒名稱：Some("main")
```

### sleep：暫停目前執行緒

`thread::sleep` 讓目前執行緒至少暫停指定的時間。實際暫停時間可能比要求的長一點（取決於作業系統排程），但不會更短。

簽名：
```rust
pub fn sleep(dur: Duration)
```

範例：
```rust
use std::thread;
use std::time::{Duration, Instant};

fn main() {
    let start = Instant::now();
    for step in 1..=3 {
        thread::sleep(Duration::from_millis(20));
        println!("第 {step} 次心跳");
    }
    println!("至少經過 60ms：{}", start.elapsed() >= Duration::from_millis(60));
}
```

輸出：
```text
第 1 次心跳
第 2 次心跳
第 3 次心跳
至少經過 60ms：true
```

### available_parallelism：查詢可用核心數

回傳這個程式能同時執行的執行緒數估計值，通常等於可用 CPU 核心數，常用來決定要開幾個工作執行緒。回傳 `io::Result<NonZero<usize>>`，在某些受限環境可能取得失敗，所以要準備預設值。

簽名：
```rust
pub fn available_parallelism() -> io::Result<NonZero<usize>>
```

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

fn main() {
    let n = thread::available_parallelism().map(|n| n.get()).unwrap_or(1);
    let workers = n.min(4);
    let handles: Vec<_> = (0..workers)
        .map(|id| thread::spawn(move || id * 100))
        .collect();
    let total: usize = handles.into_iter().map(|h| h.join().unwrap()).sum();
    let expected: usize = (0..workers).map(|id| id * 100).sum();
    println!("核心數至少 1：{}", n >= 1);
    println!("結果正確：{}", total == expected);
}
```

輸出：
```text
核心數至少 1：true
結果正確：true
```

實際核心數因機器而異，所以範例只印出檢查結果。

### thread_local!：每個執行緒一份的變數

`thread_local!` 宣告的靜態變數，每個執行緒都有自己獨立的一份，彼此互不影響，所以不需要鎖。透過 `with` 存取；通常搭配 `Cell` 或 `RefCell` 取得可變性，見 [std::cell](/pkg-cell)。

簽名：
```rust
thread_local! { static NAME: Type = init; }
impl<T: 'static> LocalKey<T> {
    pub fn with<F, R>(&'static self, f: F) -> R where F: FnOnce(&T) -> R
}
```

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

thread_local! {
    static CALLS: Cell<u32> = const { Cell::new(0) };
}

fn record() -> u32 {
    CALLS.with(|c| {
        c.set(c.get() + 1);
        c.get()
    })
}

fn main() {
    record();
    record();
    let child = thread::spawn(|| {
        record();
        CALLS.with(|c| c.get())
    });
    println!("子執行緒計數 {}", child.join().unwrap());
    println!("主執行緒計數 {}", CALLS.with(|c| c.get()));
}
```

輸出：
```text
子執行緒計數 1
主執行緒計數 2
```

## 重點整理

- `spawn` 開執行緒、`join` 等待並取回結果；不 `join` 的話主執行緒一結束子執行緒就被中止
- `spawn` 的閉包必須是 `'static`，用 `move` 交出所有權；想借用區域變數改用 `thread::scope`
- 子執行緒 panic 會讓 `join` 回傳 `Err`，不會直接拖垮整個程式
- 執行順序不確定，需要確定結果就依序 `join` 或排序
- `Builder` 可命名與設定堆疊大小，失敗時回傳 `Err` 而非 panic
- `thread_local!` 讓每個執行緒有獨立的變數，不需要鎖
