Skip to content
tezvyn:
Menu

Rust's `std::sync::Mutex`: Guarding Shared Data

Source: doc.rust-lang.orgMediumHow cards are made

A Rust Mutex guards shared data, granting access only via a temporary RAII "guard" that auto-releases the lock. It's used inside an Arc for safe multi-threaded mutation.

Why it exists

When multiple threads try to modify the same data simultaneously, it can lead to data races and unpredictable behavior. A Mutex (Mutual Exclusion) primitive was invented to solve this by ensuring only one thread can access a piece of data at any given time.

The mental model

Think of a Mutex as a room containing some data, with only one key. A thread must acquire the key to enter the room and access the data. In Rust, calling .lock() gives you a special "guard" object that holds the key. When that guard goes out of scope (e.g., at the end of a function block), the key is automatically returned, and the lock is released. This prevents you from forgetting to unlock it.

How it works

You wrap your shared data in a Mutex<T>. To access it, a thread calls the .lock() method, which blocks until the lock is available. On success, it returns a Result containing a MutexGuard. This guard is a smart pointer that lets you access the inner data. When the MutexGuard is dropped, its Drop implementation automatically releases the lock. This RAII (Resource Acquisition Is Initialization) pattern is a core safety feature of Rust's Mutex.

When to use it

Use Mutex when you need to share mutable state between threads. The most common pattern is Arc<Mutex<T>>. The Arc (Atomically Reference Counted) allows multiple threads to have shared ownership of the Mutex, and the Mutex ensures that only one thread at a time can mutate the data T inside.

When not to use it

Don't use a Mutex for sharing data that is never changed; an Arc<T> is sufficient. For simple numeric types, the more performant std::sync::atomic types are a better choice. Avoid holding a lock for long operations or across I/O, as it creates contention. The biggest footgun is relying on its "poisoning" feature for soundness. If a thread panics while holding a lock, the mutex is poisoned to signal that the data may be corrupt. However, this is an advisory mechanism and is not guaranteed to trigger in all panic scenarios, so unsafe code cannot rely on it for memory safety.

One canonical example

A common use case is a shared counter across multiple threads. The counter is wrapped in Arc::new(Mutex::new(0)). Ten threads are spawned, and each clones the Arc. Inside the thread, it calls .lock().unwrap() to get a guard, increments the number via the guard (*data += 1), and then the guard goes out of scope, releasing the lock. The .unwrap() asserts that no other thread is expected to panic while holding the lock.

Interview question

What is the primary safety benefit of Rust's MutexGuard object?

  • a.It guarantees that the data inside the Mutex remains uncorrupted even if a thread holding the lock panics.
  • b.It ensures that the locked data is always accessible by all threads, preventing deadlocks.
  • c.It allows multiple threads to read the data concurrently while blocking only write operations.
  • d.It automatically releases the lock when the MutexGuard itself goes out of scope, preventing forgotten unlocks.Correct
Why?

The card states that when the `MutexGuard` goes out of scope, the lock is automatically released, preventing forgotten unlocks. Option A is incorrect because the card explicitly warns against relying on mutex poisoning for soundness, as it's an advisory mechanism.

Just read this? Test yourself on what you have been reading.

Read the original → doc.rust-lang.org

Put your scrolling time to good use

Learn one idea, try a quiz and save useful cards for revision. Tezvyn makes it easy to learn and stay current in your tech field, a few minutes at a time.

The iPhone app is on the way

We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.

Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.

Get it on Google PlayiPhone app coming soon

We are hiring for this. Open roles that interview on rust — each one lists the topics its interview covers.

See open roles