Skip to content

Commit f3ca035

Browse files
deltragongitbot
authored and
gitbot
committed
Use scoped threads in std::sync::Barrier examples
This removes boilerplate around `Arc`s and makes the code more clear.
1 parent d95b560 commit f3ca035

File tree

1 file changed

+26
-34
lines changed

1 file changed

+26
-34
lines changed

std/src/sync/barrier.rs

+26-34
Original file line numberDiff line numberDiff line change
@@ -10,26 +10,22 @@ use crate::sync::{Condvar, Mutex};
1010
/// # Examples
1111
///
1212
/// ```
13-
/// use std::sync::{Arc, Barrier};
13+
/// use std::sync::Barrier;
1414
/// use std::thread;
1515
///
1616
/// let n = 10;
17-
/// let mut handles = Vec::with_capacity(n);
18-
/// let barrier = Arc::new(Barrier::new(n));
19-
/// for _ in 0..n {
20-
/// let c = Arc::clone(&barrier);
21-
/// // The same messages will be printed together.
22-
/// // You will NOT see any interleaving.
23-
/// handles.push(thread::spawn(move || {
24-
/// println!("before wait");
25-
/// c.wait();
26-
/// println!("after wait");
27-
/// }));
28-
/// }
29-
/// // Wait for other threads to finish.
30-
/// for handle in handles {
31-
/// handle.join().unwrap();
32-
/// }
17+
/// let barrier = Barrier::new(n);
18+
/// thread::scope(|s| {
19+
/// for _ in 0..n {
20+
/// // The same messages will be printed together.
21+
/// // You will NOT see any interleaving.
22+
/// s.spawn(|| {
23+
/// println!("before wait");
24+
/// barrier.wait();
25+
/// println!("after wait");
26+
/// });
27+
/// }
28+
/// });
3329
/// ```
3430
#[stable(feature = "rust1", since = "1.0.0")]
3531
pub struct Barrier {
@@ -105,26 +101,22 @@ impl Barrier {
105101
/// # Examples
106102
///
107103
/// ```
108-
/// use std::sync::{Arc, Barrier};
104+
/// use std::sync::Barrier;
109105
/// use std::thread;
110106
///
111107
/// let n = 10;
112-
/// let mut handles = Vec::with_capacity(n);
113-
/// let barrier = Arc::new(Barrier::new(n));
114-
/// for _ in 0..n {
115-
/// let c = Arc::clone(&barrier);
116-
/// // The same messages will be printed together.
117-
/// // You will NOT see any interleaving.
118-
/// handles.push(thread::spawn(move || {
119-
/// println!("before wait");
120-
/// c.wait();
121-
/// println!("after wait");
122-
/// }));
123-
/// }
124-
/// // Wait for other threads to finish.
125-
/// for handle in handles {
126-
/// handle.join().unwrap();
127-
/// }
108+
/// let barrier = Barrier::new(n);
109+
/// thread::scope(|s| {
110+
/// for _ in 0..n {
111+
/// // The same messages will be printed together.
112+
/// // You will NOT see any interleaving.
113+
/// s.spawn(|| {
114+
/// println!("before wait");
115+
/// barrier.wait();
116+
/// println!("after wait");
117+
/// });
118+
/// }
119+
/// });
128120
/// ```
129121
#[stable(feature = "rust1", since = "1.0.0")]
130122
pub fn wait(&self) -> BarrierWaitResult {

0 commit comments

Comments
 (0)