Send And Sync Decide Thread Safety

Probe Send and Sync bounds with compile-time assertions so thread-safety guarantees are checked when types change, not in production.

RustResilience

Code

rustsnippet
30 lines
use std::cell::RefCell;
use std::sync::{Arc, Mutex};

// 编译期探针:约束不成立时整个程序无法编译,而不是运行期才发现
fn assert_send<T: Send>() {}
fn assert_sync<T: Sync>() {}

struct Counter {
    total: u64,
}

fn main() {
    // u64 同时满足 Send 与 Sync:可以自由跨线程移动和共享
    assert_send::<u64>();
    assert_sync::<u64>();

    // RefCell 是 Send 但不是 Sync:内部可变性只允许单线程
    assert_send::<RefCell<u64>>();
    // assert_sync::<RefCell<u64>>(); // 取消注释则编译失败

    // Mutex 把内部可变性升级成线程安全:整体 Send + Sync
    assert_send::<Mutex<Counter>>();
    assert_sync::<Mutex<Counter>>();

    // Arc 再加一层共享所有权:多个线程持有同一份计数器
    assert_send::<Arc<Mutex<Counter>>>();
    assert_sync::<Arc<Mutex<Counter>>>();

    println!("all trait bounds satisfied at compile time");
}

How it works

Three functions make it happen: assert_send, assert_sync and main.

What to watch for

  • Copy, run: the standard library answers every call in the file.

Using it

Each run prints the 1 labeled block all trait bounds satisfied at compile time in source order.

Key statements

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

Interactive Tools for This Topic

FAQ

What does Send And Sync Decide Thread Safety print when run?
The script runs standalone; its 1 labeled outputs include `all trait bounds satisfied at compile time`.