Skip to content

Commit 9c8f881

Browse files
committed
Improved the example to work with mutable data, providing a reason for the mutex holding it
1 parent 95c4899 commit 9c8f881

File tree

1 file changed

+6
-4
lines changed

1 file changed

+6
-4
lines changed

src/libstd/sync/mutex.rs

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,7 @@ use crate::sys_common::poison::{self, LockResult, TryLockError, TryLockResult};
119119
/// const N: usize = 3;
120120
///
121121
/// // Some data to work with in multiple threads.
122-
/// let data_mutex = Arc::new(Mutex::new([1, 2, 3, 4]));
122+
/// let data_mutex = Arc::new(Mutex::new(vec![1, 2, 3, 4]));
123123
/// // The result of all the work across all threads.
124124
/// let res_mutex = Arc::new(Mutex::new(0));
125125
///
@@ -131,9 +131,10 @@ use crate::sys_common::poison::{self, LockResult, TryLockError, TryLockResult};
131131
/// let res_mutex_clone = Arc::clone(&res_mutex);
132132
///
133133
/// threads.push(thread::spawn(move || {
134-
/// let data = *data_mutex_clone.lock().unwrap();
134+
/// let mut data = data_mutex_clone.lock().unwrap();
135135
/// // This is the result of some important and long-ish work.
136136
/// let result = data.iter().fold(0, |acc, x| acc + x * 2);
137+
/// data.push(result);
137138
/// // We drop the `data` explicitely because it's not necessary anymore
138139
/// // and the thread still has work to do. This allow other threads to
139140
/// // start working on the data immediately, without waiting
@@ -143,9 +144,10 @@ use crate::sys_common::poison::{self, LockResult, TryLockError, TryLockResult};
143144
/// }));
144145
/// });
145146
///
146-
/// let data = *data_mutex.lock().unwrap();
147+
/// let mut data = data_mutex.lock().unwrap();
147148
/// // This is the result of some important and long-ish work.
148149
/// let result = data.iter().fold(0, |acc, x| acc + x * 2);
150+
/// data.push(result);
149151
/// // We drop the `data` explicitely because it's not necessary anymore
150152
/// // and the thread still has work to do. This allow other threads to
151153
/// // start working on the data immediately, without waiting
@@ -166,7 +168,7 @@ use crate::sys_common::poison::{self, LockResult, TryLockError, TryLockResult};
166168
/// .expect("The thread creating or execution failed !")
167169
/// });
168170
///
169-
/// assert_eq!(*res_mutex.lock().unwrap(), 80);
171+
/// assert_eq!(*res_mutex.lock().unwrap(), 800);
170172
/// ```
171173
#[stable(feature = "rust1", since = "1.0.0")]
172174
#[cfg_attr(not(test), rustc_diagnostic_item = "mutex_type")]

0 commit comments

Comments
 (0)