Rust enforces thread safety at compile time using ownership and the Send/Sync traits, whereas C++ relies on manual synchronization primitives and Java uses the JVM's garbage collector and synchronized blocks. Rust's borrow checker prevents data races by ensuring exclusive mutable access or shared immutable access, eliminating the need for runtime locks in many cases.
use std::sync::{Arc, Mutex};
use std::thread;
let counter = Arc::new(Mutex::new(0));
let mut handles = vec![];
for _ in 0..10 {
let counter = Arc::clone(&counter);
let handle = thread::spawn(move || {
let mut num = counter.lock().unwrap();
*num += 1;
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
println!("Result: {}", *counter.lock().unwrap());