Skip to content

Commit 9f94129

Browse files
committed
std: Mention clone-on-write mutation in Arc<T>
Signed-off-by: xizheyin <xizheyin@smail.nju.edu.cn>
1 parent 9038494 commit 9f94129

File tree

1 file changed

+23
-3
lines changed

1 file changed

+23
-3
lines changed

library/alloc/src/sync.rs

+23-3
Original file line numberDiff line numberDiff line change
@@ -84,9 +84,29 @@ macro_rules! acquire {
8484
///
8585
/// Shared references in Rust disallow mutation by default, and `Arc` is no
8686
/// exception: you cannot generally obtain a mutable reference to something
87-
/// inside an `Arc`. If you need to mutate through an `Arc`, use
88-
/// [`Mutex`][mutex], [`RwLock`][rwlock], or one of the [`Atomic`][atomic]
89-
/// types.
87+
/// inside an `Arc`. If you need to mutate through an `Arc`, you have several options:
88+
///
89+
/// 1. Use interior mutability with synchronization primitives like [`Mutex`][mutex],
90+
/// [`RwLock`][rwlock], or one of the [`Atomic`][atomic] types.
91+
///
92+
/// 2. Use clone-on-write semantics with [`Arc::make_mut`] which provides efficient mutation
93+
/// without requiring interior mutability. This approach clones the data only when
94+
/// needed (when there are multiple references) and can be more efficient when mutations
95+
/// are infrequent.
96+
///
97+
/// 3. Use [`Arc::get_mut`] when you know your `Arc` is not shared (has a reference count of 1),
98+
/// which provides direct mutable access to the inner value without any cloning.
99+
///
100+
/// ```
101+
/// use std::sync::Arc;
102+
///
103+
/// let mut data = Arc::new(vec![1, 2, 3]);
104+
///
105+
/// // This will clone the vector only if there are other references to it
106+
/// Arc::make_mut(&mut data).push(4);
107+
///
108+
/// assert_eq!(*data, vec![1, 2, 3, 4]);
109+
/// ```
90110
///
91111
/// **Note**: This type is only available on platforms that support atomic
92112
/// loads and stores of pointers, which includes all platforms that support

0 commit comments

Comments
 (0)