
Concurrency
Arc Mutex in Rust and the Pattern Behind Shared State
Arc gives several threads shared ownership and Mutex gives them one-at-a-time access. See the full pattern, the deadlock to avoid and what poisoning means.
9 min read
Tag
4 posts

Arc gives several threads shared ownership and Mutex gives them one-at-a-time access. See the full pattern, the deadlock to avoid and what poisoning means.

A MutexGuard held across an await can make a task non-Send or deadlock a worker. See the compiler error, the deadlock it allows and three fixes.

Use std::sync::Mutex when the lock is never held across an await and tokio::sync::Mutex when it must be. The std one is faster and is the default choice.

Share state in async code with Arc<Mutex<T>>, with a state owning task and channels, or with read heavy structures. See the trade-offs and the failure modes.