• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 use std::sync::mpsc;
2 use std::thread;
3 use std::time::Duration;
4 
5 use crossbeam_utils::sync::WaitGroup;
6 
7 const THREADS: usize = 10;
8 
9 #[test]
wait()10 fn wait() {
11     let wg = WaitGroup::new();
12     let (tx, rx) = mpsc::channel();
13 
14     for _ in 0..THREADS {
15         let wg = wg.clone();
16         let tx = tx.clone();
17 
18         thread::spawn(move || {
19             wg.wait();
20             tx.send(()).unwrap();
21         });
22     }
23 
24     thread::sleep(Duration::from_millis(100));
25 
26     // At this point, all spawned threads should be blocked, so we shouldn't get anything from the
27     // channel.
28     assert!(rx.try_recv().is_err());
29 
30     wg.wait();
31 
32     // Now, the wait group is cleared and we should receive messages.
33     for _ in 0..THREADS {
34         rx.recv().unwrap();
35     }
36 }
37 
38 #[test]
wait_and_drop()39 fn wait_and_drop() {
40     let wg = WaitGroup::new();
41     let (tx, rx) = mpsc::channel();
42 
43     for _ in 0..THREADS {
44         let wg = wg.clone();
45         let tx = tx.clone();
46 
47         thread::spawn(move || {
48             thread::sleep(Duration::from_millis(100));
49             tx.send(()).unwrap();
50             drop(wg);
51         });
52     }
53 
54     // At this point, all spawned threads should be sleeping, so we shouldn't get anything from the
55     // channel.
56     assert!(rx.try_recv().is_err());
57 
58     wg.wait();
59 
60     // Now, the wait group is cleared and we should receive messages.
61     for _ in 0..THREADS {
62         rx.try_recv().unwrap();
63     }
64 }
65