Sub topic 2
Auto Traits: How the Compiler Derives Send and Sync
Assume ownership, borrowing, lifetimes, generics, and basic thread spawning. Send and Sync are marker traits. They describe thread-safety properties without defining methods.
Auto traits and structural derivation
Rust usually derives these traits from a type's fields:
- A type is
Sendwhen its value can move to another thread safely. - A type is
Syncwhen references to it can be shared between threads safely. - A struct is usually
SendorSynconly when all relevant fields have the same property.
This is structural derivation. The compiler checks the complete type, including generic fields.
Types that are not Send or Sync
Rc<T> uses a non-atomic reference count. Moving or sharing it between threads could race, so Rc<T> is neither Send nor Sync.
Cell<T> allows mutation through a shared location. It can be Send when T is Send, but it is not Sync. RefCell<T> has the same single-threaded borrowing model.
| Type | Send | Sync | Reason |
|---|---|---|---|
| `Rc<T>` | No | No | Non-atomic reference count |
| `Cell<T>` | Sometimes | No | Unsynchronized interior mutation |
| `Mutex<T>` | If `T: Send` | If `T: Send` | Locked access |
| `AtomicUsize` | Yes | Yes | Atomic operations |
Mutex, RwLock, and atomics
Mutex<T> gives one thread mutable access at a time. RwLock<T> permits multiple readers or one writer. Atomic types provide lock-free operations for specific values, such as counters.
These types prevent data races, but they do not automatically prevent deadlocks or logical races.
Arc<Mutex<T>> and its bounds
Arc<T> provides an atomically counted shared owner. Arc<Mutex<T>> is common because Arc shares ownership while Mutex protects mutation.
The inner T must be Send. The mutex then makes the complete Arc<Mutex<T>> usable across threads.
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let value = Arc::new(Mutex::new(0));
let mut handles = Vec::new();
for _ in 0..4 {
let value = Arc::clone(&value);
handles.push(thread::spawn(move || {
*value.lock().unwrap() += 1;
}));
}
for handle in handles {
handle.join().unwrap();
}
println!("{}", *value.lock().unwrap());
}Exercise
Why can Arc<Mutex<String>> cross thread boundaries when Rc<RefCell<String>> cannot?
Show answer
Arc uses atomic reference counting and Mutex synchronizes access. Rc and RefCell are single-threaded types.