Skip to content

Commit cdf5155

Browse files
committed
Update mutex.rs
1 parent fe49947 commit cdf5155

File tree

1 file changed

+17
-15
lines changed

1 file changed

+17
-15
lines changed

library/std/src/sync/mutex.rs

Lines changed: 17 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -186,22 +186,24 @@ pub struct Mutex<T: ?Sized> {
186186

187187
/// SAFETY
188188
///
189-
/// The `Send` and `Sync` implementations for `Mutex` ensure that it is safe to
190-
/// share instances of `Mutex` between threads when the protected data is also
191-
/// thread-safe. The following explains the safety guarantees:
192-
///
193-
/// - `Send` is implemented for `Mutex<T>` if and only if `T` is also `Send`.
194-
/// This guarantees that `Mutex<T>` can be safely transferred between threads,
195-
/// and `T` can be sent across thread boundaries. This is crucial for allowing
196-
/// safe access to the protected data from multiple threads.
197-
///
198-
/// - `Sync` is implemented for `Mutex<T>` if and only if `T` is `Send`,
199-
/// since passing around a &Mutex<T> is basically the same as passing a &mut T.
200-
/// This ensures that `Mutex<T>` can be safely shared between threads
201-
/// without requiring further synchronization, assuming `T` can be sent across
202-
/// thread boundaries. It guarantees that multiple threads can safely access the
203-
/// protected data concurrently without data races.
189+
/// - impl Send for Mutex
204190
///
191+
/// Mutex is a container that wraps `T`, so it's necessary for `T` to be `Send`
192+
/// to safely send `Mutex` to another thread. This ensures that the protected
193+
/// data can be accessed safely from multiple threads without causing data races
194+
/// or other unsafe behavior.
195+
196+
///
197+
/// - impl Sync for Mutex
198+
///
199+
/// Mutex<T> provides mutable access to `T` to one thread at a time. However, it's essential
200+
/// for `T` to be `Send` because it's not safe for non-`Send` structures to be accessed in
201+
/// this manner. For instance, consider `Rc`, a non-atomic reference counted smart pointer,
202+
/// which is not `Send`. With `Rc`, we can have multiple copies pointing to the same heap
203+
/// allocation with a non-atomic reference count. If we were to use `Mutex<Rc<_>>`, it would
204+
/// only protect one instance of `Rc` from shared access, leaving other copies vulnerable
205+
/// to potential data races.
206+
205207
/// It's important to note that `Mutex` can be `Sync` even if its inner type `T`
206208
/// is not `Sync` itself. This is because `Mutex` provides a safe interface for
207209
/// accessing `T` through locking mechanisms, ensuring that only one thread can

0 commit comments

Comments
 (0)