Send 與 Sync

最後更新


Send 與 Sync 是兩個標記特徵(marker trait),編譯器靠它們判斷一個型別能不能跨執行緒移動或共享,從而在編譯期擋下資料競爭。

兩個標記特徵


標記特徵沒有任何方法,只是貼在型別上的「標籤」,告訴編譯器這個型別具備某種性質。Send 和 Sync 由編譯器自動判斷、自動實作,你幾乎不用自己寫,但會在錯誤訊息裡常常看到它們。定義見 std::marker。
特徵意思生活化比喻
Send這個值的所有權可以移到另一條執行緒東西可以打包寄給別人
Sync多條執行緒可以同時持有它的 &T東西可以放在公共桌上大家一起看

兩者的關係:T: Sync 等價於 &T: Send,也就是「把參考寄給別的執行緒是安全的」。

Send:所有權可以移到其他執行緒


thread::spawn 要求閉包和回傳值都是 Send(見執行緒)。下面的函式要求參數是 Send,大部分常見型別(整數、String、Vec、Box,以及由它們組成的元組)都符合,所以都能傳進去。
範例:
  1. use std::thread;
  2. fn run_elsewhere<T: Send + 'static + std::fmt::Debug>(value: T) {
  3. thread::spawn(move || println!("另一條執行緒收到:{:?}", value))
  4. .join()
  5. .unwrap();
  6. }
  7. fn main() {
  8. run_elsewhere(42);
  9. run_elsewhere(String::from("文字"));
  10. run_elsewhere(vec![1.5, 2.5]);
  11. run_elsewhere(Box::new((1, 'a')));
  12. }

輸出:
  1. 另一條執行緒收到:42
  2. 另一條執行緒收到:"文字"
  3. 另一條執行緒收到:[1.5, 2.5]
  4. 另一條執行緒收到:(1, 'a')

Sync:參考可以跨執行緒共享


Vec<(&str, i32)> 是 Sync,所以 &Vec 可以同時交給兩條 scoped thread 讀取。只讀的共享不會造成資料競爭,編譯器放行。
範例:
  1. use std::thread;
  2. fn main() {
  3. let table = vec![("台北", 25), ("台中", 28), ("高雄", 31)];
  4. let shared: &Vec<(&str, i32)> = &table;
  5. thread::scope(|s| {
  6. let hot = s.spawn(|| shared.iter().filter(|(_, t)| *t >= 28).count());
  7. let total = s.spawn(|| shared.iter().map(|(_, t)| t).sum::<i32>());
  8. println!("高溫城市 {} 個,溫度總和 {}", hot.join().unwrap(), total.join().unwrap());
  9. });
  10. }

輸出:
  1. 高溫城市 2 個,溫度總和 84

Rc 為什麼不能跨執行緒


Rc::clone 會把參考計數加一,這個加法是一般的「讀出、加一、寫回」。如果兩條執行緒同時對同一個 Rc 做 clone 或 drop,兩次加法可能互相覆蓋,計數就錯了:太小會提早釋放(之後讀到已釋放的記憶體),太大會洩漏。所以 Rc 既不是 Send 也不是 Sync。

編譯不過:把 Rc 送進 spawn


這段無法編譯。注意錯誤訊息直接點出是哪個型別不是 Send,以及是閉包裡哪一行用到它:
  1. use std::rc::Rc;
  2. use std::thread;
  3. fn main() {
  4. let data = Rc::new(vec![1, 2, 3]);
  5. let copy = Rc::clone(&data);
  6. let handle = thread::spawn(move || {
  7. println!("{:?}", copy);
  8. });
  9. handle.join().unwrap();
  10. }

輸出:
  1. error[E0277]: `Rc<Vec<i32>>` cannot be sent between threads safely
  2. --> err_g3.rs:7:32
  3. |
  4. 7 | let handle = thread::spawn(move || {
  5. | ------------- ^------
  6. | | |
  7. | __________________|_____________within this `{closure@err_g3.rs:7:32: 7:39}`
  8. | | |
  9. | | required by a bound introduced by this call
  10. 8 | | println!("{:?}", copy);
  11. 9 | | });
  12. | |_____^ `Rc<Vec<i32>>` cannot be sent between threads safely
  13. |
  14. = help: within `{closure@err_g3.rs:7:32: 7:39}`, the trait `Send` is not implemented for `Rc<Vec<i32>>`
  15. note: required because `copy` is used within this closure

改用 Arc


Arc 用原子操作更新計數,多條執行緒同時加減也不會錯,所以只要 T 是 Send + Sync,Arc<T> 就是 Send + Sync。把 Rc 換成 Arc,其他程式碼不用改(兩者比較見智慧指標)。
範例:
  1. use std::sync::Arc;
  2. use std::thread;
  3. fn main() {
  4. let data = Arc::new(vec![1, 2, 3]);
  5. let copy = Arc::clone(&data);
  6. let handle = thread::spawn(move || {
  7. println!("子執行緒讀到:{:?}", copy);
  8. });
  9. handle.join().unwrap();
  10. println!("主執行緒還在用:{:?},擁有者 {}", data, Arc::strong_count(&data));
  11. }

輸出:
  1. 子執行緒讀到:[1, 2, 3]
  2. 主執行緒還在用:[1, 2, 3],擁有者 1

RefCell 與 Mutex


編譯不過:RefCell 不是 Sync


RefCell 的借用計數同樣不是原子操作,所以它可以 Send(整個交給另一條執行緒),但不是 Sync(不能讓多條執行緒同時拿著 &RefCell)。下面兩條執行緒共用 &hits,這段無法編譯:
  1. use std::cell::RefCell;
  2. use std::thread;
  3. fn main() {
  4. let hits = RefCell::new(0);
  5. thread::scope(|s| {
  6. s.spawn(|| *hits.borrow_mut() += 1);
  7. s.spawn(|| *hits.borrow_mut() += 1);
  8. });
  9. println!("{}", hits.borrow());
  10. }

輸出:
  1. error[E0277]: `RefCell<i32>` cannot be shared between threads safely
  2. --> err_g5.rs:7:17
  3. |
  4. 7 | s.spawn(|| *hits.borrow_mut() += 1);
  5. | ----- ^^^^^^^^^^^^^^^^^^^^^^^^^^ `RefCell<i32>` cannot be shared between threads safely
  6. | |
  7. | required by a bound introduced by this call
  8. |
  9. = help: the trait `Sync` is not implemented for `RefCell<i32>`
  10. = note: if you want to do aliasing and mutation between multiple threads, use `std::sync::RwLock` instead
  11. = note: required for `&RefCell<i32>` to implement `Send`

改用 Mutex


Mutex<T> 是多執行緒版的 RefCell<T>:同樣提供內部可變性,但用鎖保證同一時間只有一條執行緒存取,因此只要 T: Send,Mutex<T> 就是 Sync(詳見共享狀態)。
範例:
  1. use std::sync::Mutex;
  2. use std::thread;
  3. fn main() {
  4. let hits = Mutex::new(0);
  5. thread::scope(|s| {
  6. s.spawn(|| *hits.lock().unwrap() += 1);
  7. s.spawn(|| *hits.lock().unwrap() += 1);
  8. });
  9. println!("點擊數:{}", hits.lock().unwrap());
  10. }

輸出:
  1. 點擊數:2

自動推導


結構體自動得到 Send 與 Sync


Send 和 Sync 是自動特徵(auto trait):結構體或列舉的所有欄位都是 Send,它就自動是 Send;Sync 也一樣。不必寫 derive,也沒辦法在安全程式碼裡手動加上去。
想確認某個型別是否符合,可以寫一個只有 bound、什麼都不做的空函式,讓編譯器幫你檢查:能編譯就代表符合。
範例:
  1. use std::sync::{Arc, Mutex};
  2. fn assert_send<T: Send>() {}
  3. fn assert_sync<T: Sync>() {}
  4. struct Order {
  5. id: u32,
  6. items: Vec<String>,
  7. }
  8. struct SharedCart {
  9. owner: String,
  10. items: Arc<Mutex<Vec<Order>>>,
  11. }
  12. fn main() {
  13. assert_send::<Order>();
  14. assert_sync::<Order>();
  15. assert_send::<SharedCart>();
  16. assert_sync::<SharedCart>();
  17. let order = Order { id: 7, items: vec![String::from("筆")] };
  18. let cart = SharedCart { owner: String::from("Ann"), items: Arc::new(Mutex::new(vec![order])) };
  19. let first = &cart.items.lock().unwrap()[0];
  20. println!("{} 的購物車:訂單 {} 有 {:?}", cart.owner, first.id, first.items);
  21. println!("Order 與 SharedCart 都自動是 Send + Sync");
  22. }

輸出:
  1. Ann 的購物車:訂單 7 有 ["筆"]
  2. Order 與 SharedCart 都自動是 Send + Sync

編譯不過:欄位裡有 Rc 的結構體


只要有一個欄位不是 Send,整個結構體就不是 Send。錯誤訊息會一路指到是哪個欄位造成的,這段無法編譯:
  1. use std::rc::Rc;
  2. fn assert_send<T: Send>() {}
  3. struct Session {
  4. user: Rc<String>,
  5. }
  6. fn main() {
  7. assert_send::<Session>();
  8. }

輸出:
  1. error[E0277]: `Rc<String>` cannot be sent between threads safely
  2. --> err_g8.rs:10:19
  3. |
  4. 10 | assert_send::<Session>();
  5. | ^^^^^^^ `Rc<String>` cannot be sent between threads safely
  6. |
  7. = help: within `Session`, the trait `Send` is not implemented for `Rc<String>`
  8. note: required because it appears within the type `Session`
  9. --> err_g8.rs:6:5
  10. |
  11. 5 | struct Session {
  12. 6 | user: Rc<String>,
  13. | ^^^^^^^^^^^^^^^^ required by this field

修法:把 Rc<String> 換成 Arc<String>,或乾脆直接擁有 String。

編譯器如何擋下資料競爭


整個機制只靠兩件事組合起來:
  1. 會開執行緒的 API(thread::spawn、Scope::spawn)在簽名上要求 F: Send
  2. 每個型別是不是 Send/Sync,由它的欄位自動推導,標準庫只在少數底層型別上明確標註

所以一個執行緒不安全的型別,不管被包幾層,都會在 spawn 的地方被擋下來。這個檢查完全在編譯期完成,執行時沒有任何額外成本。
型別SendSync原因
i32、String、Vec<T>(T 符合時)是是沒有共享的內部狀態
Rc<T>否否計數不是原子操作
Cell<T>、RefCell<T>是(T: Send)否透過 & 修改,沒有同步
Arc<T>是(T: Send + Sync)是(T: Send + Sync)原子計數
Mutex<T>是(T: Send)是(T: Send)鎖保證互斥
MutexGuard<T>否是(T: Sync)有些平台要求在上鎖的同一條執行緒解鎖
原始指標 *const T/*mut T否否編譯器無法得知指向的資料是否安全

注意:用 unsafe impl Send for 型別 {} 可以手動宣告,但這是在向編譯器保證「我確定它安全」,保證錯了就是未定義行為,見 unsafe Rust。

重點整理


  • Send:所有權可以移到其他執行緒;Sync:&T 可以跨執行緒共享
  • 兩者是自動特徵,所有欄位符合,型別就自動符合
  • Rc 的計數不是原子操作,所以不能跨執行緒,改用 Arc
  • RefCell 不是 Sync,多執行緒要改用 Mutex 或 RwLock
  • spawn 要求 Send,加上自動推導,資料競爭在編譯期就被擋下

資料來源