@@ -181,10 +181,23 @@ 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.
186185#[ stable( feature = "rust1" , since = "1.0.0" ) ]
187186unsafe impl < T : ?Sized + Send > Send for Mutex < T > { }
187+
188+ /// [`Mutex`] can be `Sync` if its inner type `T` is `Send`.
189+ /// This ensures that the protected data can be accessed safely from multiple threads
190+ /// without causing data races or other unsafe behavior.
191+ ///
192+ /// [`Mutex<T>`] provides mutable access to `T` to one thread at a time. However, it's essential
193+ /// for `T` to be `Send` because it's not safe for non-`Send` structures to be accessed in
194+ /// this manner. For instance, consider [`Rc`], a non-atomic reference counted smart pointer,
195+ /// which is not `Send`. With `Rc`, we can have multiple copies pointing to the same heap
196+ /// allocation with a non-atomic reference count. If we were to use `Mutex<Rc<_>>`, it would
197+ /// only protect one instance of `Rc` from shared access, leaving other copies vulnerable
198+ /// to potential data races.
199+ ///
200+ /// [`Rc`]: crate::rc::Rc
188201#[ stable( feature = "rust1" , since = "1.0.0" ) ]
189202unsafe impl < T : ?Sized + Send > Sync for Mutex < T > { }
190203
@@ -211,8 +224,16 @@ pub struct MutexGuard<'a, T: ?Sized + 'a> {
211224 poison : poison:: Guard ,
212225}
213226
227+ /// A [`MutexGuard`] is not `Send` to maximize platform portablity.
228+ /// On platforms that use POSIX thread (commonly referred to as pthreads) there is a requirement to
229+ /// release mutex locks on the same thread they were acquired.
230+ /// For this reason, [`MutexGuard`] must not implement `Send` to prevent it being dropped from
231+ /// another thread.
214232#[ stable( feature = "rust1" , since = "1.0.0" ) ]
215233impl < T : ?Sized > !Send for MutexGuard < ' _ , T > { }
234+
235+ /// `T` must be `Sync` for a [`MutexGuard<T>`] to be `Sync`
236+ /// because it is possible to get a `&T` from `&MutexGuard` (via `Deref`).
216237#[ stable( feature = "mutexguard" , since = "1.19.0" ) ]
217238unsafe impl < T : ?Sized + Sync > Sync for MutexGuard < ' _ , T > { }
218239
0 commit comments