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.
11 use kinds::{Send, Sync};
12 use sync::{Mutex, Condvar};
14 /// A barrier enables multiple tasks to synchronize the beginning
15 /// of some computation.
18 /// use std::sync::{Arc, Barrier};
19 /// use std::thread::Thread;
21 /// let barrier = Arc::new(Barrier::new(10));
22 /// for _ in range(0u, 10) {
23 /// let c = barrier.clone();
24 /// // The same messages will be printed together.
25 /// // You will NOT see any interleaving.
26 /// Thread::spawn(move|| {
27 /// println!("before wait");
29 /// println!("after wait");
34 lock: Mutex<BarrierState>,
39 unsafe impl Send for Barrier {}
40 unsafe impl Sync for Barrier {}
42 // The inner state of a double barrier
48 unsafe impl Send for BarrierState {}
49 unsafe impl Sync for BarrierState {}
52 /// Create a new barrier that can block a given number of threads.
54 /// A barrier will block `n`-1 threads which call `wait` and then wake up
55 /// all threads at once when the `n`th thread calls `wait`.
56 pub fn new(n: uint) -> Barrier {
58 lock: Mutex::new(BarrierState {
67 /// Block the current thread until all threads has rendezvoused here.
69 /// Barriers are re-usable after all threads have rendezvoused once, and can
70 /// be used continuously.
72 let mut lock = self.lock.lock().unwrap();
73 let local_gen = lock.generation_id;
75 if lock.count < self.num_threads {
76 // We need a while loop to guard against spurious wakeups.
77 // http://en.wikipedia.org/wiki/Spurious_wakeup
78 while local_gen == lock.generation_id &&
79 lock.count < self.num_threads {
80 lock = self.cvar.wait(lock).unwrap();
84 lock.generation_id += 1;
85 self.cvar.notify_all();
94 use sync::{Arc, Barrier};
95 use sync::mpsc::{channel, TryRecvError};
100 let barrier = Arc::new(Barrier::new(10));
101 let (tx, rx) = channel();
103 for _ in range(0u, 9) {
104 let c = barrier.clone();
106 Thread::spawn(move|| {
108 tx.send(true).unwrap();
112 // At this point, all spawned tasks should be blocked,
113 // so we shouldn't get anything from the port
114 assert!(match rx.try_recv() {
115 Err(TryRecvError::Empty) => true,
120 // Now, the barrier is cleared and we should get data.
121 for _ in range(0u, 9) {