Safety by exclusion

Let's talk about Mutex. Mutexes provide MUTual EXclusion among threads. Rust's Mutex works just as you'd expect coming from other programming languages. Any thread that calls a lock on a Mutex will acquire the lock or block until such a time as the thread that holds the mutex unlocks it. The type for lock is lock(&self) -> LockResult<MutexGuard<T>>. There's a neat trick happening here. LockResult<Guard> is Result<Guard>, PoisonError<Guard>>. That is, the thread that acquires a mutex lock actually gets a result, which containers the MutexGuard<T> on success or a poisoned notification. Rust poisons its mutexes when the holder of the mutex crashes, a tactic that helps prevent the continued operation of a multi-threaded propagation ...

Get Hands-On Concurrency with Rust now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.