Programming Languages
Rust
Subjective
Oct 04, 2025
How does Rust handle concurrency and what are the main concurrency primitives?
Detailed Explanation
Rust concurrency model:
• Fearless concurrency through ownership
• Send trait: types safe to transfer between threads
• Sync trait: types safe to share between threads
• No data races at compile time
• Message passing and shared state patterns
Concurrency primitives:
• std::thread: OS threads
• mpsc channels: message passing
• Mutex: mutual exclusion
• RwLock: reader-writer lock
• Arc: atomic reference counting
• Atomic types: lock-free operations
Message passing example:
use std::sync::mpsc;
use std::thread;
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
let val = String::from("hi");
tx.send(val).unwrap();
});
let received = rx.recv().unwrap();
println!("Got: {}", received);
Shared state example:
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());
Discussion (0)
No comments yet. Be the first to share your thoughts!
Share Your Thoughts