Skip to content

Commit

Permalink
Use scoped threads in std::sync::Barrier examples
Browse files Browse the repository at this point in the history
This removes boilerplate around `Arc`s and makes the code more clear.
  • Loading branch information
deltragon committed Dec 24, 2024
1 parent 32c8a9f commit 6a89f87
Showing 1 changed file with 26 additions and 34 deletions.
60 changes: 26 additions & 34 deletions library/std/src/sync/barrier.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,26 +10,22 @@ use crate::sync::{Condvar, Mutex};
/// # Examples
///
/// ```
/// use std::sync::{Arc, Barrier};
/// use std::sync::Barrier;
/// use std::thread;
///
/// let n = 10;
/// let mut handles = Vec::with_capacity(n);
/// let barrier = Arc::new(Barrier::new(n));
/// for _ in 0..n {
/// let c = Arc::clone(&barrier);
/// // The same messages will be printed together.
/// // You will NOT see any interleaving.
/// handles.push(thread::spawn(move || {
/// println!("before wait");
/// c.wait();
/// println!("after wait");
/// }));
/// }
/// // Wait for other threads to finish.
/// for handle in handles {
/// handle.join().unwrap();
/// }
/// let barrier = Barrier::new(n);
/// thread::scope(|s| {
/// for _ in 0..n {
/// // The same messages will be printed together.
/// // You will NOT see any interleaving.
/// s.spawn(|| {
/// println!("before wait");
/// barrier.wait();
/// println!("after wait");
/// });
/// }
/// });
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Barrier {
Expand Down Expand Up @@ -105,26 +101,22 @@ impl Barrier {
/// # Examples
///
/// ```
/// use std::sync::{Arc, Barrier};
/// use std::sync::Barrier;
/// use std::thread;
///
/// let n = 10;
/// let mut handles = Vec::with_capacity(n);
/// let barrier = Arc::new(Barrier::new(n));
/// for _ in 0..n {
/// let c = Arc::clone(&barrier);
/// // The same messages will be printed together.
/// // You will NOT see any interleaving.
/// handles.push(thread::spawn(move || {
/// println!("before wait");
/// c.wait();
/// println!("after wait");
/// }));
/// }
/// // Wait for other threads to finish.
/// for handle in handles {
/// handle.join().unwrap();
/// }
/// let barrier = Barrier::new(n);
/// thread::scope(|s| {
/// for _ in 0..n {
/// // The same messages will be printed together.
/// // You will NOT see any interleaving.
/// s.spawn(|| {
/// println!("before wait");
/// barrier.wait();
/// println!("after wait");
/// });
/// }
/// });
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn wait(&self) -> BarrierWaitResult {
Expand Down

0 comments on commit 6a89f87

Please sign in to comment.