The two foundational auto-traits that guarantee multi-threaded memory safety and compile-out data races.
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
// Arc<Mutex<T>> is Send + Sync, safe across threads
let counter = Arc::new(Mutex::new(0));
let mut handles = vec![];
for _ in 0..5 {
let counter_clone = Arc::clone(&counter);
handles.push(thread::spawn(move || {
let mut num = counter_clone.lock().unwrap();
*num += 1;
}));
}
for h in handles { h.join().unwrap(); }
println!("Final count: {}", *counter.lock().unwrap());
}Rust achieves 'Fearless Concurrency' through its type system. Concurrency bugs like data races are caught during compilation rather than producing production crashes.
`Send` and `Sync` are 'Auto Traits': if all fields in a struct implement `Send`, the parent struct automatically implements `Send` without manual boilerplate.
If you attempt to send an `Rc<T>` across a thread, the compiler halts with error 'E0277: Rc<T> cannot be sent between threads safely' because incrementing non-atomic reference counters from two threads simultaneously causes a data race.
A data race occurs when 2 or more pointers access the same memory location concurrently, at least one access is a write, and there is no synchronization. Rust makes this impossible in safe code.
// Raw pointers are !Send and !Sync:
struct RawHandle {
ptr: *mut u8, // Prevent accidental cross-thread transmission
}