1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
12 use sync::{Mutex, Condvar};
14 /// A barrier enables multiple threads to synchronize the beginning
15 /// of some computation.
20 /// use std::sync::{Arc, Barrier};
23 /// let mut handles = Vec::with_capacity(10);
24 /// let barrier = Arc::new(Barrier::new(10));
26 /// let c = barrier.clone();
27 /// // The same messages will be printed together.
28 /// // You will NOT see any interleaving.
29 /// handles.push(thread::spawn(move|| {
30 /// println!("before wait");
32 /// println!("after wait");
35 /// // Wait for other threads to finish.
36 /// for handle in handles {
37 /// handle.join().unwrap();
40 #[stable(feature = "rust1", since = "1.0.0")]
42 lock: Mutex<BarrierState>,
47 // The inner state of a double barrier
53 /// A result returned from wait.
55 /// Currently this opaque structure only has one method, [`.is_leader()`]. Only
56 /// one thread will receive a result that will return `true` from this function.
58 /// [`.is_leader()`]: #method.is_leader
63 /// use std::sync::Barrier;
65 /// let barrier = Barrier::new(1);
66 /// let barrier_wait_result = barrier.wait();
68 #[stable(feature = "rust1", since = "1.0.0")]
69 pub struct BarrierWaitResult(bool);
71 #[stable(feature = "std_debug", since = "1.16.0")]
72 impl fmt::Debug for Barrier {
73 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
74 f.pad("Barrier { .. }")
79 /// Creates a new barrier that can block a given number of threads.
81 /// A barrier will block `n`-1 threads which call [`wait`] and then wake up
82 /// all threads at once when the `n`th thread calls [`wait`].
84 /// [`wait`]: #method.wait
89 /// use std::sync::Barrier;
91 /// let barrier = Barrier::new(10);
93 #[stable(feature = "rust1", since = "1.0.0")]
94 pub fn new(n: usize) -> Barrier {
96 lock: Mutex::new(BarrierState {
100 cvar: Condvar::new(),
105 /// Blocks the current thread until all threads have rendezvoused here.
107 /// Barriers are re-usable after all threads have rendezvoused once, and can
108 /// be used continuously.
110 /// A single (arbitrary) thread will receive a [`BarrierWaitResult`] that
111 /// returns `true` from [`is_leader`] when returning from this function, and
112 /// all other threads will receive a result that will return `false` from
115 /// [`BarrierWaitResult`]: struct.BarrierWaitResult.html
116 /// [`is_leader`]: struct.BarrierWaitResult.html#method.is_leader
121 /// use std::sync::{Arc, Barrier};
124 /// let mut handles = Vec::with_capacity(10);
125 /// let barrier = Arc::new(Barrier::new(10));
127 /// let c = barrier.clone();
128 /// // The same messages will be printed together.
129 /// // You will NOT see any interleaving.
130 /// handles.push(thread::spawn(move|| {
131 /// println!("before wait");
133 /// println!("after wait");
136 /// // Wait for other threads to finish.
137 /// for handle in handles {
138 /// handle.join().unwrap();
141 #[stable(feature = "rust1", since = "1.0.0")]
142 pub fn wait(&self) -> BarrierWaitResult {
143 let mut lock = self.lock.lock().unwrap();
144 let local_gen = lock.generation_id;
146 if lock.count < self.num_threads {
147 // We need a while loop to guard against spurious wakeups.
148 // http://en.wikipedia.org/wiki/Spurious_wakeup
149 while local_gen == lock.generation_id &&
150 lock.count < self.num_threads {
151 lock = self.cvar.wait(lock).unwrap();
153 BarrierWaitResult(false)
156 lock.generation_id += 1;
157 self.cvar.notify_all();
158 BarrierWaitResult(true)
163 #[stable(feature = "std_debug", since = "1.16.0")]
164 impl fmt::Debug for BarrierWaitResult {
165 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
166 f.debug_struct("BarrierWaitResult")
167 .field("is_leader", &self.is_leader())
172 impl BarrierWaitResult {
173 /// Returns whether this thread from [`wait`] is the "leader thread".
175 /// Only one thread will have `true` returned from their result, all other
176 /// threads will have `false` returned.
178 /// [`wait`]: struct.Barrier.html#method.wait
183 /// use std::sync::Barrier;
185 /// let barrier = Barrier::new(1);
186 /// let barrier_wait_result = barrier.wait();
187 /// println!("{:?}", barrier_wait_result.is_leader());
189 #[stable(feature = "rust1", since = "1.0.0")]
190 pub fn is_leader(&self) -> bool { self.0 }
195 use sync::{Arc, Barrier};
196 use sync::mpsc::{channel, TryRecvError};
200 #[cfg_attr(target_os = "emscripten", ignore)]
204 let barrier = Arc::new(Barrier::new(N));
205 let (tx, rx) = channel();
208 let c = barrier.clone();
210 thread::spawn(move|| {
211 tx.send(c.wait().is_leader()).unwrap();
215 // At this point, all spawned threads should be blocked,
216 // so we shouldn't get anything from the port
217 assert!(match rx.try_recv() {
218 Err(TryRecvError::Empty) => true,
222 let mut leader_found = barrier.wait().is_leader();
224 // Now, the barrier is cleared and we should get data.
226 if rx.recv().unwrap() {
227 assert!(!leader_found);
231 assert!(leader_found);