Rust Reference ยท Standard Library Modules
The std::sync module
Reference for std::sync: Arc, Mutex, RwLock, Condvar, Barrier, Once, OnceLock, LazyLock, lock poisoning and the rules for sharing data between threads.
std::sync holds the tools for sharing data between threads safely. Arc<T> gives several threads shared ownership. Mutex<T> lets one thread at a time access the value inside; RwLock<T> allows many readers or one writer. Condvar lets a thread sleep until a condition changes, Barrier makes a group of threads wait for each other, and Once, OnceLock and LazyLock run initialization exactly once.
The key design point is that a lock owns its data: you cannot reach the value without locking, and the lock is released when the returned guard is dropped. The module also contains the mpsc channels and atomic types, which have their own pages.
use std::sync::{Arc, Mutex}; let counter = Arc::new(Mutex::new(0)); *counter.lock().unwrap() += 1;
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
| Type | Key methods | Notes |
|---|---|---|
Arc<T> |
new, clone, strong_count, try_unwrap, get_mut, make_mut |
Atomic reference counting; T must be Send + Sync for the Arc to be Send. |
Mutex<T> |
new, lock, try_lock, into_inner, get_mut, is_poisoned, clear_poison |
lock() -> LockResult<MutexGuard<T>>; blocks. |
RwLock<T> |
read, write, try_read, try_write |
Many readers or one writer; writer starvation behavior is platform-defined. |
Condvar |
wait, wait_while, wait_timeout, notify_one, notify_all |
Always used with a Mutex guard. |
Barrier |
new(n), wait() |
wait returns a BarrierWaitResult whose is_leader() is true for one thread. |
Once |
call_once, is_completed |
Run a closure once. |
OnceLock<T> |
get, set, get_or_init |
Thread-safe write-once cell (static-friendly). |
LazyLock<T> |
LazyLock::new(f), deref |
Initialized on first use; stable since Rust 1.80. |
Weak<T> |
upgrade |
Non-owning pointer to an Arc. |
Errors and edge cases: lock() returns Err(PoisonError) if a thread panicked while holding the lock; into_inner() on the error recovers the guard. Locking a Mutex twice on the same thread deadlocks or panics (unspecified). try_lock returns TryLockError::WouldBlock rather than waiting.
Usage notes
- Keep critical sections short and never hold a guard across a slow call (I/O, sleep) or an
.await. - Lock ordering matters: if two threads take locks A and B in opposite orders, they can deadlock. Pick a global order.
- Poisoning is a safety net, not a requirement.
lock().unwrap()is idiomatic when a panic elsewhere should crash this thread too; useunwrap_or_else(|e| e.into_inner())when the data stays valid. - Wrap a
Condvarwait in a loop or usewait_while; spurious wake-ups are allowed. - For a plain counter or flag, an atomic is cheaper than a
Mutex; see std::sync::atomic. Arc<Mutex<T>>is the common shape;Arc<RwLock<T>>pays off only when reads greatly outnumber writes.OnceLockandLazyLockreplace the oldlazy_staticcrate for most global state.- Since Rust 1.63
Mutex::new,RwLock::newandCondvar::newareconst, so they can initialize astaticdirectly.