Skip to content

Commit

Permalink
docs: Documented Send and Sync requirements for Mutex + MutexGuard
Browse files Browse the repository at this point in the history
  • Loading branch information
ranger-ross committed Jan 18, 2025
1 parent 8e59cf9 commit 068039b
Showing 1 changed file with 26 additions and 2 deletions.
28 changes: 26 additions & 2 deletions library/std/src/sync/poison/mutex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -181,10 +181,24 @@ pub struct Mutex<T: ?Sized> {
data: UnsafeCell<T>,
}

// these are the only places where `T: Send` matters; all other
// functionality works fine on a single thread.
/// Mutex is a container that wraps `T`, so it's necessary for `T` to be `Send`
/// to safely send `Mutex` to another thread. This ensures that the protected
/// data can be accessed safely from multiple threads without causing data races
/// or other unsafe behavior.
///
/// [`Mutex<T>`] provides mutable access to `T` to one thread at a time. However, it's essential
/// for `T` to be `Send` because it's not safe for non-`Send` structures to be accessed in
/// this manner. For instance, consider [`Rc`], a non-atomic reference counted smart pointer,
/// which is not `Send`. With `Rc`, we can have multiple copies pointing to the same heap
/// allocation with a non-atomic reference count. If we were to use `Mutex<Rc<_>>`, it would
/// only protect one instance of `Rc` from shared access, leaving other copies vulnerable
/// to potential data races.
#[stable(feature = "rust1", since = "1.0.0")]
unsafe impl<T: ?Sized + Send> Send for Mutex<T> {}

/// [`Mutex`] can be `Sync` even if its inner type `T` is not `Sync` itself.
/// This is because [`Mutex`] provides a safe interface for accessing `T` through
/// locking mechanisms, ensuring that only one thread can access `T` at a time.
#[stable(feature = "rust1", since = "1.0.0")]
unsafe impl<T: ?Sized + Send> Sync for Mutex<T> {}

Expand All @@ -211,8 +225,18 @@ pub struct MutexGuard<'a, T: ?Sized + 'a> {
poison: poison::Guard,
}

/// A [`MutexGuard`] is not `Send` to maximize platform portablity.
/// On platforms that use POSIX thread (commonly referred to as pthreads) there is a requirement to
/// release mutex locks on the same thread they were acquired.
/// For this reason, [`MutexGuard`] must not implement `Send` to prevent it being dropped from
/// another thread.
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: ?Sized> !Send for MutexGuard<'_, T> {}

/// A [`MutexGuard`] can be `Sync` even though it is not `Send` because ownership is not transfer to
/// a new thread. Because ownership always stays on the original thread `Sync`
/// is safe to implement for [`MutexGuard`].
/// See the `!Send` implementation on [`MutexGuard`] for more details.
#[stable(feature = "mutexguard", since = "1.19.0")]
unsafe impl<T: ?Sized + Sync> Sync for MutexGuard<'_, T> {}

Expand Down

0 comments on commit 068039b

Please sign in to comment.