Skip to content

Commit 162ae1b

Browse files
committed
docs: Documented Send and Sync requirements for Mutex + MutexGuard
1 parent 8e59cf9 commit 162ae1b

File tree

1 file changed

+28
-2
lines changed

1 file changed

+28
-2
lines changed

library/std/src/sync/poison/mutex.rs

+28-2
Original file line numberDiff line numberDiff line change
@@ -181,10 +181,28 @@ pub struct Mutex<T: ?Sized> {
181181
data: UnsafeCell<T>,
182182
}
183183

184-
// these are the only places where `T: Send` matters; all other
185-
// functionality works fine on a single thread.
184+
/// A [`Mutex`] is safe to send to other threads by design.
185+
///
186+
/// `T` must be `Send` for a [`Mutex`] to be `Send` because it is possible to acquire
187+
/// the owned `T` from the `Mutex` via [`into_inner`].
188+
///
189+
/// [`into_inner`]: Mutex::into_inner
186190
#[stable(feature = "rust1", since = "1.0.0")]
187191
unsafe impl<T: ?Sized + Send> Send for Mutex<T> {}
192+
193+
/// [`Mutex`] can be `Sync` if its inner type `T` is `Send`.
194+
/// This ensures that the protected data can be accessed safely from multiple threads
195+
/// without causing data races or other unsafe behavior.
196+
///
197+
/// [`Mutex<T>`] provides mutable access to `T` to one thread at a time. However, it's essential
198+
/// for `T` to be `Send` because it's not safe for non-`Send` structures to be accessed in
199+
/// this manner. For instance, consider [`Rc`], a non-atomic reference counted smart pointer,
200+
/// which is not `Send`. With `Rc`, we can have multiple copies pointing to the same heap
201+
/// allocation with a non-atomic reference count. If we were to use `Mutex<Rc<_>>`, it would
202+
/// only protect one instance of `Rc` from shared access, leaving other copies vulnerable
203+
/// to potential data races.
204+
///
205+
/// [`Rc`]: crate::rc::Rc
188206
#[stable(feature = "rust1", since = "1.0.0")]
189207
unsafe impl<T: ?Sized + Send> Sync for Mutex<T> {}
190208

@@ -211,8 +229,16 @@ pub struct MutexGuard<'a, T: ?Sized + 'a> {
211229
poison: poison::Guard,
212230
}
213231

232+
/// A [`MutexGuard`] is not `Send` to maximize platform portablity.
233+
/// On platforms that use POSIX thread (commonly referred to as pthreads) there is a requirement to
234+
/// release mutex locks on the same thread they were acquired.
235+
/// For this reason, [`MutexGuard`] must not implement `Send` to prevent it being dropped from
236+
/// another thread.
214237
#[stable(feature = "rust1", since = "1.0.0")]
215238
impl<T: ?Sized> !Send for MutexGuard<'_, T> {}
239+
240+
/// `T` must be `Sync` for a [`MutexGuard<T>`] to be `Sync`
241+
/// because it is possible to get a `&T` from `&MutexGuard` (via `Deref`).
216242
#[stable(feature = "mutexguard", since = "1.19.0")]
217243
unsafe impl<T: ?Sized + Sync> Sync for MutexGuard<'_, T> {}
218244

0 commit comments

Comments
 (0)