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 ...
Safety by exclusion
Get Hands-On Concurrency with Rust now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.