std::sync: Arc, Mutex, and channels

Arc and Mutex for shared mutation across threads, mutex poisoning, and mpsc send/recv synchronized without sleep.

Arc<T> is a thread-safe reference-counted pointer. Cloning an Arc shares the same allocation; it does not clone T. Arc does not make T automatically safe to mutate from multiple threads. If T is not Sync, or if you need mutation, you still need interior mutability such as Mutex<T>. Arc<Mutex<i32>> is the usual shared counter. The first example increments under the lock and prints only after every handle has been joined, so the total is 3 regardless of scheduling.

If a thread panics while holding a Mutex, later lock calls return Err(PoisonError). The example joins the panicking thread first, then uses into_inner to recover the value. mpsc is included here as the standard multi-producer channel; send and recv provide the synchronization, without sleep.

Examples were compiled with rustc 1.90.0 using --edition=2024 and run as a plain binary. See the Rust 1.90.0 documentation for the complete API.

Rust reference overview →

API index

APISummary
Arc::new, Arc::clone, Mutex::new, Mutex::lock, PoisonError::into_innerShare 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.
mpsc::channel, Sender::send, Receiver::recv, Receiver::iterSend values on a channel and wait with recv. After the last sender is dropped, recv returns an error instead of blocking forever.

Arc, Mutex, and poisoning

Each spawned thread receives its own Arc clone and increments the mutex-protected counter. After all joins, the lock is acquired on the original Arc and the value is 3. That pattern is race-free: the increment happens under lock, and the print happens after join. lock().unwrap() panics if the mutex is poisoned. When a thread panics while holding the lock, the example matches on Err and prints the recovered value 1 with into_inner, rather than asserting panic-hook text.

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.

ParameterDescription
data / tThe 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.
rust
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 1

Related: thread::spawn and join, Rc and RefCell

Official documentation →

mpsc channels

mpsc::channel creates a sender and a receiver. A single sender delivers values in send order, so the two recv calls print 1 then 2 after the worker has sent them. The worker is then joined. The second half drops the sender; rx.iter() yields the already-sent 7 and ends, and a later recv is Err because the channel is disconnected. No sleep is used.

mpsc::channel, Sender::send, Receiver::recv, Receiver::iter

pub fn channel<T>() -> (Sender<T>, Receiver<T>)
pub fn send(&self, t: T) -> Result<(), SendError<T>>
pub fn recv(&self) -> Result<T, RecvError>

Send values on a channel and wait with recv. After the last sender is dropped, recv returns an error instead of blocking forever.

ParameterDescription
tThe value to send. It must be Send to move it to the receiving thread.

Returns: send returns Err if all receivers have been dropped. recv returns Ok(value) or Err if all senders have been dropped.

Errors and panics

  • RecvError — Returned by recv when every sender has been dropped and the channel is empty. The example reports is_err and does not depend on the display string.
  • This page does not cover sync_channel or the async runtimes. The channel is used only to show blocking recv and disconnect, synchronized without sleep.
rust
use std::sync::mpsc;
use std::thread;

fn main() {
    let (tx, rx) = mpsc::channel();
    let worker = thread::spawn(move || {
        tx.send(1).unwrap();
        tx.send(2).unwrap();
    });
    println!("{} {}", rx.recv().unwrap(), rx.recv().unwrap());
    worker.join().unwrap();

    let (tx, rx) = mpsc::channel();
    tx.send(7).unwrap();
    drop(tx);
    let got: Vec<i32> = rx.iter().collect();
    println!("{:?}", got);
    println!("{}", rx.recv().is_err());
}

Expected output

1 2
[7]
true

Related: thread::spawn and join

Official documentation →