# Send 與 Sync

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

## 兩個標記特徵

標記特徵沒有任何方法，只是貼在型別上的「標籤」，告訴編譯器這個型別具備某種性質。`Send` 和 `Sync` 由編譯器自動判斷、自動實作，你幾乎不用自己寫，但會在錯誤訊息裡常常看到它們。定義見 [std::marker](/pkg-marker)。

| 特徵 | 意思 | 生活化比喻 |
| --- | --- | --- |
| `Send` | 這個值的所有權可以移到另一條執行緒 | 東西可以打包寄給別人 |
| `Sync` | 多條執行緒可以同時持有它的 `&T` | 東西可以放在公共桌上大家一起看 |

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

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

`thread::spawn` 要求閉包和回傳值都是 `Send`（見[執行緒](/concurrency-threads)）。下面的函式要求參數是 `Send`，大部分常見型別（整數、`String`、`Vec`、`Box`，以及由它們組成的元組）都符合，所以都能傳進去。

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

fn run_elsewhere<T: Send + 'static + std::fmt::Debug>(value: T) {
    thread::spawn(move || println!("另一條執行緒收到：{:?}", value))
        .join()
        .unwrap();
}

fn main() {
    run_elsewhere(42);
    run_elsewhere(String::from("文字"));
    run_elsewhere(vec![1.5, 2.5]);
    run_elsewhere(Box::new((1, 'a')));
}
```

輸出：
```text
另一條執行緒收到：42
另一條執行緒收到："文字"
另一條執行緒收到：[1.5, 2.5]
另一條執行緒收到：(1, 'a')
```

### Sync：參考可以跨執行緒共享

`Vec<(&str, i32)>` 是 `Sync`，所以 `&Vec` 可以同時交給兩條 scoped thread 讀取。只讀的共享不會造成資料競爭，編譯器放行。

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

fn main() {
    let table = vec![("台北", 25), ("台中", 28), ("高雄", 31)];
    let shared: &Vec<(&str, i32)> = &table;

    thread::scope(|s| {
        let hot = s.spawn(|| shared.iter().filter(|(_, t)| *t >= 28).count());
        let total = s.spawn(|| shared.iter().map(|(_, t)| t).sum::<i32>());
        println!("高溫城市 {} 個，溫度總和 {}", hot.join().unwrap(), total.join().unwrap());
    });
}
```

輸出：
```text
高溫城市 2 個，溫度總和 84
```

## Rc 為什麼不能跨執行緒

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

### 編譯不過：把 Rc 送進 spawn

這段無法編譯。注意錯誤訊息直接點出是哪個型別不是 `Send`，以及是閉包裡哪一行用到它：

```rust
use std::rc::Rc;
use std::thread;

fn main() {
    let data = Rc::new(vec![1, 2, 3]);
    let copy = Rc::clone(&data);
    let handle = thread::spawn(move || {
        println!("{:?}", copy);
    });
    handle.join().unwrap();
}
```

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

### 改用 Arc

`Arc` 用原子操作更新計數，多條執行緒同時加減也不會錯，所以只要 `T` 是 `Send + Sync`，`Arc<T>` 就是 `Send + Sync`。把 `Rc` 換成 `Arc`，其他程式碼不用改（兩者比較見[智慧指標](/smart-pointers-overview)）。

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

fn main() {
    let data = Arc::new(vec![1, 2, 3]);
    let copy = Arc::clone(&data);
    let handle = thread::spawn(move || {
        println!("子執行緒讀到：{:?}", copy);
    });
    handle.join().unwrap();
    println!("主執行緒還在用：{:?}，擁有者 {}", data, Arc::strong_count(&data));
}
```

輸出：
```text
子執行緒讀到：[1, 2, 3]
主執行緒還在用：[1, 2, 3]，擁有者 1
```

## RefCell 與 Mutex

### 編譯不過：RefCell 不是 Sync

`RefCell` 的借用計數同樣不是原子操作，所以它可以 `Send`（整個交給另一條執行緒），但不是 `Sync`（不能讓多條執行緒同時拿著 `&RefCell`）。下面兩條執行緒共用 `&hits`，這段無法編譯：

```rust
use std::cell::RefCell;
use std::thread;

fn main() {
    let hits = RefCell::new(0);
    thread::scope(|s| {
        s.spawn(|| *hits.borrow_mut() += 1);
        s.spawn(|| *hits.borrow_mut() += 1);
    });
    println!("{}", hits.borrow());
}
```

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

### 改用 Mutex

`Mutex<T>` 是多執行緒版的 `RefCell<T>`：同樣提供內部可變性，但用鎖保證同一時間只有一條執行緒存取，因此只要 `T: Send`，`Mutex<T>` 就是 `Sync`（詳見[共享狀態](/concurrency-shared-state)）。

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

fn main() {
    let hits = Mutex::new(0);
    thread::scope(|s| {
        s.spawn(|| *hits.lock().unwrap() += 1);
        s.spawn(|| *hits.lock().unwrap() += 1);
    });
    println!("點擊數：{}", hits.lock().unwrap());
}
```

輸出：
```text
點擊數：2
```

## 自動推導

### 結構體自動得到 Send 與 Sync

`Send` 和 `Sync` 是自動特徵（auto trait）：結構體或列舉的所有欄位都是 `Send`，它就自動是 `Send`；`Sync` 也一樣。不必寫 `derive`，也沒辦法在安全程式碼裡手動加上去。

想確認某個型別是否符合，可以寫一個只有 bound、什麼都不做的空函式，讓編譯器幫你檢查：能編譯就代表符合。

範例：
```rust
use std::sync::{Arc, Mutex};

fn assert_send<T: Send>() {}
fn assert_sync<T: Sync>() {}

struct Order {
    id: u32,
    items: Vec<String>,
}

struct SharedCart {
    owner: String,
    items: Arc<Mutex<Vec<Order>>>,
}

fn main() {
    assert_send::<Order>();
    assert_sync::<Order>();
    assert_send::<SharedCart>();
    assert_sync::<SharedCart>();

    let order = Order { id: 7, items: vec![String::from("筆")] };
    let cart = SharedCart { owner: String::from("Ann"), items: Arc::new(Mutex::new(vec![order])) };
    let first = &cart.items.lock().unwrap()[0];
    println!("{} 的購物車：訂單 {} 有 {:?}", cart.owner, first.id, first.items);
    println!("Order 與 SharedCart 都自動是 Send + Sync");
}
```

輸出：
```text
Ann 的購物車：訂單 7 有 ["筆"]
Order 與 SharedCart 都自動是 Send + Sync
```

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

只要有一個欄位不是 `Send`，整個結構體就不是 `Send`。錯誤訊息會一路指到是哪個欄位造成的，這段無法編譯：

```rust
use std::rc::Rc;

fn assert_send<T: Send>() {}

struct Session {
    user: Rc<String>,
}

fn main() {
    assert_send::<Session>();
}
```

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

修法：把 `Rc<String>` 換成 `Arc<String>`，或乾脆直接擁有 `String`。

## 編譯器如何擋下資料競爭

整個機制只靠兩件事組合起來：

1. 會開執行緒的 API（`thread::spawn`、`Scope::spawn`）在簽名上要求 `F: Send`
2. 每個型別是不是 `Send`／`Sync`，由它的欄位自動推導，標準庫只在少數底層型別上明確標註

所以一個執行緒不安全的型別，不管被包幾層，都會在 `spawn` 的地方被擋下來。這個檢查完全在編譯期完成，執行時沒有任何額外成本。

| 型別 | Send | Sync | 原因 |
| --- | --- | --- | --- |
| `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](/lowlevel-unsafe)。

## 重點整理

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

## 資料來源

- [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/)
