Shared-State Concurrency
Unlike message passing’s single ownership model, shared-state concurrency allows multiple threads to access the same memory locations simultaneously. Rust provides thread-safe primitives through mutexes and atomic reference counting.
Mutexes for Exclusive Data Access
A mutex (mutual exclusion) guards data with a locking mechanism, ensuring only one thread accesses the data at a time.
use std::sync::Mutex; fn main() { let m = Mutex::new(5); { let mut num = m.lock().unwrap(); *num = 6; } println!("m = {m:?}"); }
Key Mutex<T>
characteristics:
lock()
returnsLockResult<MutexGuard<T>>
MutexGuard<T>
implementsDeref
to access inner dataDrop
implementation automatically releases the lock when guard goes out of scope- Lock acquisition blocks until available or panics if poisoned
Sharing Mutexes Between Threads
Attempting to share a mutex across threads fails without proper ownership handling:
use std::sync::Mutex;
use std::thread;
fn main() {
let counter = Mutex::new(0);
let mut handles = vec![];
for _ in 0..10 {
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());
}
Error: cannot move counter
into multiple threads:
$ cargo run
Compiling shared-state v0.1.0 (file:///projects/shared-state)
error[E0382]: borrow of moved value: `counter`
--> src/main.rs:21:29
|
5 | let counter = Mutex::new(0);
| ------- move occurs because `counter` has type `Mutex<i32>`, which does not implement the `Copy` trait
...
8 | for _ in 0..10 {
| -------------- inside of this loop
9 | let handle = thread::spawn(move || {
| ------- value moved into closure here, in previous iteration of loop
...
21 | println!("Result: {}", *counter.lock().unwrap());
| ^^^^^^^ value borrowed here after move
|
help: consider moving the expression out of the loop so it is only moved once
|
8 ~ let mut value = counter.lock();
9 ~ for _ in 0..10 {
10 | let handle = thread::spawn(move || {
11 ~ let mut num = value.unwrap();
|
For more information about this error, try `rustc --explain E0382`.
error: could not compile `shared-state` (bin "shared-state") due to 1 previous error
Multiple Ownership with Rc<T>
Limitation
Rc<T>
provides multiple ownership but is not thread-safe:
use std::rc::Rc;
use std::sync::Mutex;
use std::thread;
fn main() {
let counter = Rc::new(Mutex::new(0));
let mut handles = vec![];
for _ in 0..10 {
let counter = Rc::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());
}
Error: Rc<T>
lacks Send
trait for thread safety:
$ cargo run
Compiling shared-state v0.1.0 (file:///projects/shared-state)
error[E0277]: `Rc<Mutex<i32>>` cannot be sent between threads safely
--> src/main.rs:11:36
|
11 | let handle = thread::spawn(move || {
| ------------- ^------
| | |
| ______________________|_____________within this `{closure@src/main.rs:11:36: 11:43}`
| | |
| | required by a bound introduced by this call
12 | | let mut num = counter.lock().unwrap();
13 | |
14 | | *num += 1;
15 | | });
| |_________^ `Rc<Mutex<i32>>` cannot be sent between threads safely
|
= help: within `{closure@src/main.rs:11:36: 11:43}`, the trait `Send` is not implemented for `Rc<Mutex<i32>>`
note: required because it's used within this closure
--> src/main.rs:11:36
|
11 | let handle = thread::spawn(move || {
| ^^^^^^^
note: required by a bound in `spawn`
--> /rustc/4eb161250e340c8f48f66e2b929ef4a5bed7c181/library/std/src/thread/mod.rs:728:1
For more information about this error, try `rustc --explain E0277`.
error: could not compile `shared-state` (bin "shared-state") due to 1 previous error
Rc<T>
uses non-atomic reference counting, making it unsafe for concurrent access.
Atomic Reference Counting with Arc<T>
Arc<T>
(atomically reference-counted) provides thread-safe multiple ownership:
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 = 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()); }
Arc<T>
uses atomic operations for reference counting, ensuring thread safety. Atomic operations have performance overhead, so use only when needed for concurrent access.
Interior Mutability Pattern
Mutex<T>
provides interior mutability similar to RefCell<T>
:
RefCell<T>
/Rc<T>
: Single-threaded shared ownership with runtime borrow checkingMutex<T>
/Arc<T>
: Multi-threaded shared ownership with locking
Both patterns allow mutation through immutable references, but Mutex<T>
includes deadlock risks when acquiring multiple locks.