Skip to content

update mutex docs for send & sync #123225

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions library/std/src/sync/mutex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -183,8 +183,35 @@ pub struct Mutex<T: ?Sized> {

// these are the only places where `T: Send` matters; all other
// functionality works fine on a single thread.

/// SAFETY
///
/// - impl Send for Mutex
///
/// 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.

///
/// - impl Sync for Mutex
///
/// `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.

/// It's important to note that `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.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This note is great, but it should also be moved to impl Sync for Mutex.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

okay

///
#[stable(feature = "rust1", since = "1.0.0")]
unsafe impl<T: ?Sized + Send> Send for Mutex<T> {}

#[stable(feature = "rust1", since = "1.0.0")]
unsafe impl<T: ?Sized + Send> Sync for Mutex<T> {}

Expand Down
Loading
Loading