Concurrency & Fearless ThreadsIntermediate
1Question 1 of 1
rustHow does 'Fearless Concurrency' work in Rust with Send and Sync traits?
Explanation & Concept
Rust guarantees thread safety at compile-time via two auto traits:
• `Send`: Indicates ownership of the type can be transferred across thread boundaries. • `Sync`: Indicates it is safe to share references to the type across multiple threads (`&T` is `Send`).
If you attempt to share a non-thread-safe type (like `Rc<T>`) across threads, the code fails to compile.
Code Example
rust
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let counter = Arc::new(Mutex::new(0));
let mut handles = vec![];
for _ in 0..10 {
let counter_ref = Arc::clone(&counter);
handles.push(thread::spawn(move || {
let mut num = counter_ref.lock().unwrap();
*num += 1;
}));
}
for handle in handles { handle.join().unwrap(); }
println!("Result: {}", *counter.lock().unwrap()); // 10
}How It Works & Key Takeaways
Because `Mutex` unlocks automatically when its guard goes out of scope, deadlocks and unreleased mutexes are avoided.
Mock Test · 1 Questions · Optional
Ready for Closures?
Take a quick test to evaluate yourself, or move straight to the next module.
Intermediate1 questions