Okay, let's break down Rust's Send and Sync traits and how they relate to types like Cell, RefCell, Rc, and Arc.
These traits are fundamental to Rust's "fearless concurrency" guarantees, enforced by the compiler.
1. Send Trait
- Meaning: A type
T is Send if it is safe to transfer ownership of a value of type T to another thread.
- Think: "Sendable". Can I
send this value completely to a different thread?
- Examples:
- Most primitive types (
i32, f64, bool, String, Vec<t> if T is Send).
Arc<t> (if T is Send + Sync).
- Non-Examples:
Rc<t> (its reference count is not atomic, so transferring ownership could lead to race conditions if the original thread still held another Rc to the same data).
- Raw pointers (
*mut T, *const T) are inherently unsafe and thus not Send by default.
- How it's used: When you use
std::thread::spawn, any variables moved into the closure must be Send.
2. Sync Trait
- Meaning: A type
T is Sync if it is safe to share references (&T) of a value of type T across multiple threads concurrently.
- Think: "Synchronized" or "Shareable (via immutable reference)". If multiple threads have a
&T, is it safe?
- Requirement: For
T to be Sync, &T must be Send. This means a shared reference itself must be safe to send to another thread.
- Examples:
- Most primitive types (
i32, f64, bool, String).
Vec<t> (if T is Sync). You can share &Vec<t> across threads, and threads can read elements concurrently safely.
Arc<t> (if T is Send + Sync). Multiple threads can hold references (Arc itself acts like a shared reference) to the same Arc.
Mutex<t> (if T is Send). A Mutex provides synchronization, making shared access safe.
RwLock<t> (if T is Send + Sync).
- Non-Examples:
Cell<t>, RefCell<t> (they allow interior mutability without synchronization suitable for multiple threads).
Rc<t> (non-atomic reference count cannot be safely manipulated by multiple threads via shared references).
- Raw pointers (
*mut T, *const T).
- How it's used: Crucial for types that will be accessed (read or mutated via interior mutability patterns) from multiple threads simultaneously, often via
Arc.
Key Points about Send and Sync:
- Marker Traits: They have no methods; they just "mark" a type with certain properties.
- Auto Traits: Usually, the compiler automatically implements
Send and Sync for your types if all their constituent fields are Send and Sync, respectively.
- Unsafe: You can implement them unsafely (
unsafe impl Send for MyType {}), but you must guarantee that doing so upholds the safety invariants. This is rarely needed and requires extreme care.
Relationship with Cell, RefCell, Rc, Arc:
Let's look at each of these types in the context of Send and Sync:
-
Rc<t> (Reference Counted Pointer)
- Purpose: Single-threaded shared ownership. Allows multiple owners of the same data on the same thread, and the data is dropped when the last
Rc pointing to it is dropped.
- Mechanism: Uses a non-atomic reference count. Incrementing/decrementing this count is not thread-safe.
Send? No. Sending an Rc to another thread could lead to data races on the reference count if both threads try to clone or drop their Rcs concurrently.
Sync? No. Sharing &Rc<t> across threads is unsafe for the same reason – concurrent access to the non-atomic reference count.
-
Arc<t> (Atomically Reference Counted Pointer)
- Purpose: Thread-safe shared ownership. Allows multiple owners across multiple threads.
- Mechanism: Uses an atomic reference count. Operations on this count use atomic CPU instructions, which are safe to perform concurrently from multiple threads.
Send? Yes, if T: Send + Sync. You can send an Arc to another thread. The inner data T must also be safe to potentially send (Send) and share (Sync) because different threads holding the Arc might access T.
Sync? Yes, if T: Send + Sync. You can share Arc<t> (or &Arc<t>) across threads safely because the reference counting is atomic. Again, access to the underlying T requires T itself to be safe for sharing (Sync) and potentially sending (Send).
-
Cell<t>
- Purpose: Single-threaded interior mutability (changing inner data through a shared reference
&Cell<t>). Disables compile-time borrow checks, relying on methods like set() and get() (for T: Copy) or replace(), take(). No runtime overhead for borrowing checks.
Summary & How they Fit Together:
Send and Sync enforce thread safety at compile time.
Rc, Cell, and RefCell are designed for single-threaded scenarios. They lack the necessary synchronization (atomic operations or locks) to be used directly for sharing or shared mutation across threads. Specifically:
Rc is !Send and !Sync.
Cell and RefCell are Send (if T: Send) but crucially !Sync.
Arc is the thread-safe counterpart to Rc, enabling shared ownership across threads (Send + Sync if T: Send + Sync).
- To achieve thread-safe interior mutability (like
Cell/RefCell but across threads), you need synchronization primitives like Mutex<t> or RwLock<t>. These types are Sync (if T meets their bounds, typically T: Send), allowing them to be shared safely across threads, often wrapped in an Arc:
Arc<mutex<t>>: Allows shared ownership (Arc), and safe mutation (Mutex) from any thread holding the Arc.
Arc<rwlock<t>>: Allows shared ownership</rwlock</mutex