]>
git.proxmox.com Git - rustc.git/blob - vendor/crossbeam-utils-0.6.5/src/sync/wait_group.rs
2 use std
::sync
::{Arc, Condvar, Mutex}
;
4 /// Enables threads to synchronize the beginning or end of some computation.
6 /// # Wait groups vs barriers
8 /// `WaitGroup` is very similar to [`Barrier`], but there are a few differences:
10 /// * `Barrier` needs to know the number of threads at construction, while `WaitGroup` is cloned to
11 /// register more threads.
13 /// * A `Barrier` can be reused even after all threads have synchronized, while a `WaitGroup`
14 /// synchronizes threads only once.
16 /// * All threads wait for others to reach the `Barrier`. With `WaitGroup`, each thread can choose
17 /// to either wait for other threads or to continue without blocking.
22 /// use crossbeam_utils::sync::WaitGroup;
25 /// // Create a new wait group.
26 /// let wg = WaitGroup::new();
29 /// // Create another reference to the wait group.
30 /// let wg = wg.clone();
32 /// thread::spawn(move || {
35 /// // Drop the reference to the wait group.
40 /// // Block until all threads have finished their work.
44 /// [`Barrier`]: https://doc.rust-lang.org/std/sync/struct.Barrier.html
45 pub struct WaitGroup
{
49 /// Inner state of a `WaitGroup`.
56 /// Creates a new wait group and returns the single reference to it.
61 /// use crossbeam_utils::sync::WaitGroup;
63 /// let wg = WaitGroup::new();
65 pub fn new() -> WaitGroup
{
67 inner
: Arc
::new(Inner
{
74 /// Drops this reference and waits until all other references are dropped.
79 /// use crossbeam_utils::sync::WaitGroup;
82 /// let wg = WaitGroup::new();
85 /// let wg = wg.clone();
87 /// // Block until both threads have reached `wait()`.
92 /// // Block until both threads have reached `wait()`.
96 if *self.inner
.count
.lock().unwrap() == 1 {
100 let inner
= self.inner
.clone();
103 let mut count
= inner
.count
.lock().unwrap();
105 count
= inner
.cvar
.wait(count
).unwrap();
110 impl Drop
for WaitGroup
{
112 let mut count
= self.inner
.count
.lock().unwrap();
116 self.inner
.cvar
.notify_all();
121 impl Clone
for WaitGroup
{
122 fn clone(&self) -> WaitGroup
{
123 let mut count
= self.inner
.count
.lock().unwrap();
127 inner
: self.inner
.clone(),
132 impl fmt
::Debug
for WaitGroup
{
133 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
134 let count
: &usize = &*self.inner
.count
.lock().unwrap();
135 f
.debug_struct("WaitGroup")
136 .field("count", count
)