2 use crate::sync::{Condvar, Mutex};
4 /// A barrier enables multiple threads to synchronize the beginning
5 /// of some computation.
10 /// use std::sync::{Arc, Barrier};
13 /// let mut handles = Vec::with_capacity(10);
14 /// let barrier = Arc::new(Barrier::new(10));
16 /// let c = barrier.clone();
17 /// // The same messages will be printed together.
18 /// // You will NOT see any interleaving.
19 /// handles.push(thread::spawn(move|| {
20 /// println!("before wait");
22 /// println!("after wait");
25 /// // Wait for other threads to finish.
26 /// for handle in handles {
27 /// handle.join().unwrap();
30 #[stable(feature = "rust1", since = "1.0.0")]
32 lock: Mutex<BarrierState>,
37 // The inner state of a double barrier
43 /// A `BarrierWaitResult` is returned by [`wait`] when all threads in the [`Barrier`]
44 /// have rendezvoused.
46 /// [`wait`]: struct.Barrier.html#method.wait
47 /// [`Barrier`]: struct.Barrier.html
52 /// use std::sync::Barrier;
54 /// let barrier = Barrier::new(1);
55 /// let barrier_wait_result = barrier.wait();
57 #[stable(feature = "rust1", since = "1.0.0")]
58 pub struct BarrierWaitResult(bool);
60 #[stable(feature = "std_debug", since = "1.16.0")]
61 impl fmt::Debug for Barrier {
62 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63 f.pad("Barrier { .. }")
68 /// Creates a new barrier that can block a given number of threads.
70 /// A barrier will block `n`-1 threads which call [`wait`] and then wake up
71 /// all threads at once when the `n`th thread calls [`wait`].
73 /// [`wait`]: #method.wait
78 /// use std::sync::Barrier;
80 /// let barrier = Barrier::new(10);
82 #[stable(feature = "rust1", since = "1.0.0")]
83 pub fn new(n: usize) -> Barrier {
85 lock: Mutex::new(BarrierState { count: 0, generation_id: 0 }),
91 /// Blocks the current thread until all threads have rendezvoused here.
93 /// Barriers are re-usable after all threads have rendezvoused once, and can
94 /// be used continuously.
96 /// A single (arbitrary) thread will receive a [`BarrierWaitResult`] that
97 /// returns `true` from [`is_leader`] when returning from this function, and
98 /// all other threads will receive a result that will return `false` from
101 /// [`BarrierWaitResult`]: struct.BarrierWaitResult.html
102 /// [`is_leader`]: struct.BarrierWaitResult.html#method.is_leader
107 /// use std::sync::{Arc, Barrier};
110 /// let mut handles = Vec::with_capacity(10);
111 /// let barrier = Arc::new(Barrier::new(10));
113 /// let c = barrier.clone();
114 /// // The same messages will be printed together.
115 /// // You will NOT see any interleaving.
116 /// handles.push(thread::spawn(move|| {
117 /// println!("before wait");
119 /// println!("after wait");
122 /// // Wait for other threads to finish.
123 /// for handle in handles {
124 /// handle.join().unwrap();
127 #[stable(feature = "rust1", since = "1.0.0")]
128 pub fn wait(&self) -> BarrierWaitResult {
129 let mut lock = self.lock.lock().unwrap();
130 let local_gen = lock.generation_id;
132 if lock.count < self.num_threads {
133 // We need a while loop to guard against spurious wakeups.
134 // http://en.wikipedia.org/wiki/Spurious_wakeup
135 while local_gen == lock.generation_id && lock.count < self.num_threads {
136 lock = self.cvar.wait(lock).unwrap();
138 BarrierWaitResult(false)
141 lock.generation_id = lock.generation_id.wrapping_add(1);
142 self.cvar.notify_all();
143 BarrierWaitResult(true)
148 #[stable(feature = "std_debug", since = "1.16.0")]
149 impl fmt::Debug for BarrierWaitResult {
150 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
151 f.debug_struct("BarrierWaitResult").field("is_leader", &self.is_leader()).finish()
155 impl BarrierWaitResult {
156 /// Returns `true` if this thread from [`wait`] is the "leader thread".
158 /// Only one thread will have `true` returned from their result, all other
159 /// threads will have `false` returned.
161 /// [`wait`]: struct.Barrier.html#method.wait
166 /// use std::sync::Barrier;
168 /// let barrier = Barrier::new(1);
169 /// let barrier_wait_result = barrier.wait();
170 /// println!("{:?}", barrier_wait_result.is_leader());
172 #[stable(feature = "rust1", since = "1.0.0")]
173 pub fn is_leader(&self) -> bool {
180 use crate::sync::mpsc::{channel, TryRecvError};
181 use crate::sync::{Arc, Barrier};
185 #[cfg_attr(target_os = "emscripten", ignore)]
189 let barrier = Arc::new(Barrier::new(N));
190 let (tx, rx) = channel();
193 let c = barrier.clone();
195 thread::spawn(move || {
196 tx.send(c.wait().is_leader()).unwrap();
200 // At this point, all spawned threads should be blocked,
201 // so we shouldn't get anything from the port
202 assert!(matches!(rx.try_recv(), Err(TryRecvError::Empty)));
204 let mut leader_found = barrier.wait().is_leader();
206 // Now, the barrier is cleared and we should get data.
208 if rx.recv().unwrap() {
209 assert!(!leader_found);
213 assert!(leader_found);