std::sync

最後更新


在多個執行緒之間安全共享資料的工具:共享所有權、鎖、條件變數與一次性初始化。

這個模組做什麼


用 std::thread 開了多個執行緒之後,常會遇到「大家要讀寫同一份資料」。Rust 不允許沒有保護的共享可變狀態,所以要用這個模組的型別把資料包起來。
型別用途比喻
Arc<T>多個執行緒共同擁有同一個值多人共用一把鑰匙圈
Mutex<T>同一時間只有一個執行緒能存取只有一間的廁所
RwLock<T>多個讀者或一個寫者圖書館:大家可同時看,改書要清場
Condvar等待某個條件成立再繼續等號碼牌叫號
Barrier等所有執行緒到齊再一起出發集合點
OnceLock<T>只初始化一次的全域值開幕剪綵只剪一次
LazyLock<T>第一次使用時才初始化的全域值用到才開燈

單執行緒的版本是 std::rc 的 Rc 與 std::cell 的 RefCell;只需要共享一個整數或布林值時,std::sync::atomic 更輕量;要在執行緒間傳訊息見 std::sync::mpsc。

匯入


  1. use std::sync::{Arc, Mutex, RwLock, Condvar, Barrier, OnceLock, LazyLock};

常用 API


Arc:跨執行緒的共享所有權


Arc(Atomically Reference Counted)讓多個擁有者共享同一個值,最後一個擁有者消失時才釋放。Arc::clone 只增加計數,不複製資料。Arc<T> 只提供 &T,要修改內容需要再搭配 Mutex 或原子型別。
簽名:
  1. impl<T> Arc<T> {
  2. pub fn new(data: T) -> Arc<T>
  3. pub fn strong_count(this: &Arc<T>) -> usize
  4. }

範例:
  1. use std::sync::Arc;
  2. use std::thread;
  3. fn main() {
  4. let config = Arc::new(vec!["db=main", "port=5432"]);
  5. let handles: Vec<_> = (0..3)
  6. .map(|id| {
  7. let cfg = Arc::clone(&config);
  8. thread::spawn(move || format!("worker {id} 讀到 {} 筆設定", cfg.len()))
  9. })
  10. .collect();
  11. for h in handles {
  12. println!("{}", h.join().unwrap());
  13. }
  14. println!("剩餘擁有者:{}", Arc::strong_count(&config));
  15. }

輸出:
  1. worker 0 讀到 2 筆設定
  2. worker 1 讀到 2 筆設定
  3. worker 2 讀到 2 筆設定
  4. 剩餘擁有者:1

Mutex:互斥鎖


lock() 取得鎖並回傳 MutexGuard,它像 &mut T 一樣可以讀寫;guard 離開作用域時自動解鎖。其他執行緒呼叫 lock() 會阻塞直到鎖被釋放。Arc<Mutex<T>> 是多執行緒共享可變資料最常見的組合。
注意:lock() 回傳 LockResult,持鎖執行緒 panic 時會得到 Err(見下方「毒化」)。同一執行緒在已持有鎖時再次 lock() 會死結(deadlock)或 panic。
簽名:
  1. impl<T> Mutex<T> {
  2. pub const fn new(t: T) -> Mutex<T>
  3. pub fn lock(&self) -> LockResult<MutexGuard<'_, T>>
  4. }

範例:
  1. use std::sync::{Arc, Mutex};
  2. use std::thread;
  3. fn main() {
  4. let total = Arc::new(Mutex::new(0u64));
  5. let handles: Vec<_> = (1..=4)
  6. .map(|n| {
  7. let total = Arc::clone(&total);
  8. thread::spawn(move || {
  9. for _ in 0..1000 {
  10. *total.lock().unwrap() += n;
  11. }
  12. })
  13. })
  14. .collect();
  15. for h in handles {
  16. h.join().unwrap();
  17. }
  18. println!("total = {}", *total.lock().unwrap());
  19. }

輸出:
  1. total = 10000

RwLock:讀寫鎖


讀多寫少的資料用 RwLock:read() 允許多個讀者同時持有,write() 則獨占。讀者與寫者不能同時存在。
簽名:
  1. impl<T> RwLock<T> {
  2. pub const fn new(t: T) -> RwLock<T>
  3. pub fn read(&self) -> LockResult<RwLockReadGuard<'_, T>>
  4. pub fn write(&self) -> LockResult<RwLockWriteGuard<'_, T>>
  5. }

範例:
  1. use std::collections::BTreeMap;
  2. use std::sync::RwLock;
  3. use std::thread;
  4. fn main() {
  5. let prices = RwLock::new(BTreeMap::from([("咖啡", 60), ("紅茶", 40)]));
  6. thread::scope(|s| {
  7. for _ in 0..3 {
  8. s.spawn(|| {
  9. let r = prices.read().unwrap();
  10. assert_eq!(r.len(), 2);
  11. });
  12. }
  13. });
  14. prices.write().unwrap().insert("咖啡", 65);
  15. let r = prices.read().unwrap();
  16. let r2 = prices.read().unwrap();
  17. println!("{:?}", *r);
  18. println!("兩個讀鎖同時存在:{}", r.len() == r2.len());
  19. }

輸出:
  1. {"咖啡": 65, "紅茶": 40}
  2. 兩個讀鎖同時存在:true

Condvar:等待條件成立


Condvar(條件變數)讓執行緒睡著等待,直到另一個執行緒改變狀態並通知它。它一定和 Mutex 搭配:wait 會釋放鎖並睡眠,被喚醒時重新取得鎖。wait_while 會在條件成立時持續等待,自動處理「假喚醒(spurious wakeup)」。
簽名:
  1. impl Condvar {
  2. pub const fn new() -> Condvar
  3. pub fn wait_while<'a, T, F>(&self, guard: MutexGuard<'a, T>, condition: F)
  4. -> LockResult<MutexGuard<'a, T>>
  5. where F: FnMut(&mut T) -> bool
  6. pub fn notify_one(&self)
  7. pub fn notify_all(&self)
  8. }

範例:
  1. use std::sync::{Arc, Condvar, Mutex};
  2. use std::thread;
  3. fn main() {
  4. let pair = Arc::new((Mutex::new(None::<String>), Condvar::new()));
  5. let pair2 = Arc::clone(&pair);
  6. let waiter = thread::spawn(move || {
  7. let (lock, cvar) = &*pair2;
  8. let guard = cvar.wait_while(lock.lock().unwrap(), |v| v.is_none()).unwrap();
  9. format!("收到:{}", guard.as_deref().unwrap())
  10. });
  11. {
  12. let (lock, cvar) = &*pair;
  13. *lock.lock().unwrap() = Some(String::from("資料準備好了"));
  14. cvar.notify_one();
  15. }
  16. println!("{}", waiter.join().unwrap());
  17. }

輸出:
  1. 收到:資料準備好了

即使通知比等待先發生也沒關係:wait_while 先檢查條件,資料已經是 Some 就不會睡。

Barrier:等所有人到齊


Barrier::new(n) 建立一個集合點,前 n - 1 個呼叫 wait() 的執行緒會阻塞,第 n 個到達時全部一起放行。適合「每一輪都要等大家算完才進下一輪」的分階段計算。
簽名:
  1. impl Barrier {
  2. pub const fn new(n: usize) -> Barrier
  3. pub fn wait(&self) -> BarrierWaitResult
  4. }

範例:
  1. use std::sync::{Barrier, Mutex};
  2. use std::thread;
  3. fn main() {
  4. let barrier = Barrier::new(3);
  5. let log = Mutex::new(Vec::new());
  6. let leaders = thread::scope(|s| {
  7. let hs: Vec<_> = (0..3)
  8. .map(|id| {
  9. let (barrier, log) = (&barrier, &log);
  10. s.spawn(move || {
  11. log.lock().unwrap().push(format!("階段一 #{id}"));
  12. let r = barrier.wait();
  13. log.lock().unwrap().push(format!("階段二 #{id}"));
  14. r.is_leader()
  15. })
  16. })
  17. .collect();
  18. hs.into_iter().map(|h| h.join().unwrap()).filter(|&b| b).count()
  19. });
  20. let log = log.into_inner().unwrap();
  21. let first_phase2 = log.iter().position(|e| e.starts_with("階段二")).unwrap();
  22. println!("階段一全部在階段二之前:{}", first_phase2 == 3);
  23. println!("leader 數量:{leaders}");
  24. }

輸出:
  1. 階段一全部在階段二之前:true
  2. leader 數量:1

wait() 回傳的結果中恰好有一個執行緒是 leader,可以讓它負責每輪的收尾工作。

OnceLock 與 Once:只初始化一次


OnceLock<T>(Rust 1.70 起)是一個只能寫入一次的容器,常放在 static 裡當全域設定。get_or_init 第一次呼叫時執行初始化,之後都直接回傳同一個值;多個執行緒同時呼叫也只會初始化一次。只需要「執行一次某段程式」而不存值時,可用較底層的 Once::call_once。
簽名:
  1. impl<T> OnceLock<T> {
  2. pub const fn new() -> OnceLock<T>
  3. pub fn get(&self) -> Option<&T>
  4. pub fn set(&self, value: T) -> Result<(), T>
  5. pub fn get_or_init<F>(&self, f: F) -> &T where F: FnOnce() -> T
  6. }

範例:
  1. use std::sync::OnceLock;
  2. use std::thread;
  3. static APP_NAME: OnceLock<String> = OnceLock::new();
  4. fn name() -> &'static str {
  5. APP_NAME.get_or_init(|| {
  6. println!("初始化中...");
  7. String::from("rust-shop")
  8. })
  9. }
  10. fn main() {
  11. println!("初始化前:{:?}", APP_NAME.get());
  12. let hs: Vec<_> = (0..3).map(|_| thread::spawn(name)).collect();
  13. for h in hs {
  14. println!("{}", h.join().unwrap());
  15. }
  16. println!("再次 set:{:?}", APP_NAME.set(String::from("other")));
  17. }

輸出:
  1. 初始化前:None
  2. 初始化中...
  3. rust-shop
  4. rust-shop
  5. rust-shop
  6. 再次 set:Err("other")

LazyLock:第一次使用時才初始化


LazyLock<T>(Rust 1.80 起)在宣告時就給定初始化函式,第一次解參考時才執行,之後像一般的 &T 使用。比 OnceLock 更方便,適合「初始化方式固定」的全域資料,例如查表。
簽名:
  1. impl<T, F: FnOnce() -> T> LazyLock<T, F> {
  2. pub const fn new(f: F) -> LazyLock<T, F>
  3. }

範例:
  1. use std::collections::BTreeMap;
  2. use std::sync::LazyLock;
  3. static UNITS: LazyLock<BTreeMap<&str, u32>> = LazyLock::new(|| {
  4. println!("建立單位表");
  5. BTreeMap::from([("m", 1), ("km", 1000), ("mile", 1609)])
  6. });
  7. fn main() {
  8. println!("程式開始");
  9. println!("1 km = {} m", UNITS["km"]);
  10. println!("單位數 {}", UNITS.len());
  11. }

輸出:
  1. 程式開始
  2. 建立單位表
  3. 1 km = 1000 m
  4. 單位數 3

毒化(poison):持鎖時 panic


如果執行緒在持有 Mutex 或 RwLock 時 panic,鎖會被標記為「毒化」,之後的 lock() 都回傳 Err(PoisonError),提醒你資料可能只改到一半。你可以用 into_inner() 從錯誤中取回 guard 繼續使用,或用 clear_poison()(Rust 1.77 起)在修復資料後解除標記。
範例用 panic::set_hook 關閉預設的 panic 訊息輸出。
簽名:
  1. impl<T> Mutex<T> {
  2. pub fn is_poisoned(&self) -> bool
  3. pub fn clear_poison(&self)
  4. }
  5. impl<T> PoisonError<T> {
  6. pub fn into_inner(self) -> T
  7. }

範例:
  1. use std::panic;
  2. use std::sync::Mutex;
  3. use std::thread;
  4. fn main() {
  5. panic::set_hook(Box::new(|_| {}));
  6. let balance = Mutex::new(100);
  7. let r = thread::scope(|s| {
  8. s.spawn(|| {
  9. let mut g = balance.lock().unwrap();
  10. *g -= 30;
  11. panic!("轉帳中斷");
  12. })
  13. .join()
  14. });
  15. println!("子執行緒成功:{}", r.is_ok());
  16. println!("已毒化:{}", balance.is_poisoned());
  17. let value = match balance.lock() {
  18. Ok(g) => *g,
  19. Err(poisoned) => *poisoned.into_inner(),
  20. };
  21. println!("目前餘額:{value}");
  22. balance.clear_poison();
  23. println!("解除後:{}", balance.lock().is_ok());
  24. }

輸出:
  1. 子執行緒成功:false
  2. 已毒化:true
  3. 目前餘額:70
  4. 解除後:true

重點整理


  • Arc 共享所有權但只給 &T,要修改就搭配 Mutex、RwLock 或原子型別
  • Mutex 的 guard 離開作用域自動解鎖;同一執行緒重複 lock() 會死結
  • Condvar 一定搭配 Mutex,用 wait_while 避免假喚醒與「通知先到」的問題
  • 全域值用 OnceLock(手動初始化)或 LazyLock(宣告時給定初始化函式)
  • 持鎖時 panic 會毒化鎖,lock() 回傳 Err,可用 into_inner 取回資料