執行緒

最後更新


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

為什麼需要執行緒


一個程式啟動時只有一條「主執行緒」,所有程式碼依序執行。現在的 CPU 有多個核心,如果工作可以拆開(例如算兩段範圍的質數、同時處理多個檔案),就能開更多執行緒,讓多個核心一起做。
名詞意思
並行(concurrency)多個工作在同一段時間內都有進展
平行(parallelism)多個工作真的在不同核心上同時執行
資料競爭(data race)兩個執行緒同時存取同一份資料,且至少一個在寫,結果無法預測

Rust 標準庫的 std::thread 建立的是作業系統執行緒,每條都有自己的堆疊,由作業系統排程。API 細節見 std::thread。

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


thread::spawn 接收一個閉包,在新執行緒執行並立刻回傳 JoinHandle;主執行緒可以繼續做別的事。之後呼叫 join() 等那條執行緒結束,並取得閉包的回傳值。
注意:main 結束時整個程式就結束,還沒跑完的子執行緒會直接被終止,所以要等結果就一定要 join。子執行緒 panic 時,join 會回傳 Err,不會連帶讓主執行緒 panic。
範例:
  1. use std::thread;
  2. fn count_primes(from: u32, to: u32) -> usize {
  3. (from..to)
  4. .filter(|&n| n >= 2 && (2..n).take_while(|d| d * d <= n).all(|d| n % d != 0))
  5. .count()
  6. }
  7. fn main() {
  8. let first = thread::spawn(|| count_primes(0, 50_000));
  9. let second = thread::spawn(|| count_primes(50_000, 100_000));
  10. let a = first.join().unwrap();
  11. let b = second.join().unwrap();
  12. println!("前半 {a} 個、後半 {b} 個,共 {} 個質數", a + b);
  13. }

輸出:
  1. 前半 5133 個、後半 4459 個,共 9592 個質數

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

把資料交給執行緒


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


thread::spawn 要求閉包是 'static:不能借用任何可能比執行緒先消失的東西。編譯器不知道子執行緒會跑多久,萬一 main 先結束、names 被釋放,子執行緒手上就是一個懸垂參考。下面這段無法編譯:
  1. use std::thread;
  2. fn main() {
  3. let names = vec!["Ann", "Bob"];
  4. let handle = thread::spawn(|| {
  5. println!("{:?}", names);
  6. });
  7. handle.join().unwrap();
  8. }

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

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

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


加上 move,閉包取得 names 的所有權,資料跟著執行緒走,活多久都沒問題。代價是 main 之後不能再用 names;要拿回結果,就讓閉包回傳它,再從 join 取得。
範例:
  1. use std::thread;
  2. fn main() {
  3. let names = vec!["Ann", "Bob"];
  4. let handle = thread::spawn(move || {
  5. println!("子執行緒拿到:{:?}", names);
  6. names.len()
  7. });
  8. let n = handle.join().unwrap();
  9. println!("子執行緒回傳 {n} 個名字");
  10. }

輸出:
  1. 子執行緒拿到:["Ann", "Bob"]
  2. 子執行緒回傳 2 個名字

多條執行緒都要讀同一份資料時,move 一份給一條不夠用,這時改用 Arc 共享所有權,見智慧指標與共享狀態。

scoped thread:保證先結束,就能借用


thread::scope(Rust 1.63 起)開一個作用域,裡面用 s.spawn 開的執行緒保證在 scope 回傳前全部結束。既然執行緒不會活得比區域變數久,閉包就可以直接借用,不必 move 也不必 Arc,原本的變數之後照常使用。
範例:
  1. use std::thread;
  2. fn main() {
  3. let numbers = vec![3, 1, 4, 1, 5, 9, 2, 6];
  4. let mut summary = String::new();
  5. thread::scope(|s| {
  6. let sum = s.spawn(|| numbers.iter().sum::<i32>());
  7. let max = s.spawn(|| *numbers.iter().max().unwrap());
  8. summary = format!("總和 {}、最大 {}", sum.join().unwrap(), max.join().unwrap());
  9. });
  10. println!("{summary}");
  11. println!("numbers 仍屬於 main:{:?}", numbers);
  12. }

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

無畏並行


其他語言裡,資料競爭往往要到正式環境、偶爾當機時才發現。Rust 把同一套借用規則延伸到執行緒:「同時多個讀,或只有一個寫」在編譯期就檢查。能編譯的安全 Rust 程式不會有資料競爭,這就是「無畏並行(fearless concurrency)」:可以放心改寫並行程式,編譯器會把關。
注意:無畏並行保證沒有資料競爭,但不保證沒有死結或邏輯錯誤(例如鎖的順序錯了),見共享狀態。

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


兩條執行緒都想 push 到 results,等於同時存在兩個 &mut,違反「只有一個寫」。在 C 或 Go 裡這會編譯成功、執行時偶爾壞掉;在 Rust 這段無法編譯:
  1. use std::thread;
  2. fn main() {
  3. let mut results = Vec::new();
  4. thread::scope(|s| {
  5. s.spawn(|| results.push(1));
  6. s.spawn(|| results.push(2));
  7. });
  8. println!("{:?}", results);
  9. }

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

修法有三種:讓每條執行緒回傳自己的結果再由 join 收集;用訊息傳遞把結果送回來;或用 Mutex 保護共享的 Vec(見共享狀態)。

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


如果每條執行緒只碰自己那一段,就不需要任何鎖。chunks_mut 把切片分成互不重疊的 &mut [T],編譯器知道它們不重疊,所以允許各自交給不同執行緒修改(切片見切片型別)。
範例:
  1. use std::thread;
  2. fn main() {
  3. let mut pixels = vec![10u8, 20, 30, 40, 50, 60, 70, 80];
  4. thread::scope(|s| {
  5. for chunk in pixels.chunks_mut(3) {
  6. s.spawn(move || {
  7. for p in chunk.iter_mut() {
  8. *p = 255 - *p;
  9. }
  10. });
  11. }
  12. });
  13. println!("{:?}", pixels);
  14. }

輸出:
  1. [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 起)保證執行緒先結束,因此可以直接借用
  • 借用規則延伸到執行緒,資料競爭在編譯期就被擋下
  • 能切開的資料就切開各自處理,最不需要同步

資料來源