Arc::new, Arc::clone, Mutex::new, Mutex::lock, PoisonError::into_inner
pub fn new(data: T) -> Arc<T>
pub fn clone(this: &Arc<T>) -> Arc<T>
pub const fn new(t: T) -> Mutex<T>
pub fn lock(&self) -> LockResult<MutexGuard<'_, T>>
pub fn into_inner(self) -> MutexGuard<'_, T>Share a Mutex across threads with Arc. A panic while the lock is held poisons the mutex; into_inner still gives access to the guarded value.
| Parameter | Description |
|---|---|
data / t | The value placed in the Arc or Mutex. Mutex<T> requires T: Send to move the mutex to another thread. |
Returns: lock returns Ok(MutexGuard) or Err(PoisonError). The guard dereferences to T. into_inner on the poison error yields the same kind of guard.
Errors and panics
PoisonError— Returned by lock after a panic while the mutex was held. Official documentation describes this as poisoning. The example recovers with into_inner after joining the panicking thread.
- A silent panic hook is used only so the intentional panic is observed through join and poisoning, without hook text on stderr.
- Arc alone does not serialize writes to T. Use Mutex or another synchronization type when more than one thread mutates the data.
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let counter = Arc::new(Mutex::new(0));
let mut handles = Vec::new();
for _ in 0..3 {
let shared = Arc::clone(&counter);
handles.push(thread::spawn(move || {
*shared.lock().unwrap() += 1;
}));
}
for handle in handles {
handle.join().unwrap();
}
println!("{}", *counter.lock().unwrap());
std::panic::set_hook(Box::new(|_| {}));
let mutex = Arc::new(Mutex::new(1));
let in_thread = Arc::clone(&mutex);
let _ = thread::spawn(move || {
let _guard = in_thread.lock().unwrap();
panic!("hold");
})
.join();
match mutex.lock() {
Ok(_) => println!("ok"),
Err(poisoned) => println!("poisoned {}", *poisoned.into_inner()),
}
}Expected output
3
poisoned 1Related: thread::spawn and join, Rc and RefCell