]> git.lizzy.rs Git - rust.git/blob - src/libstd/sync/condvar.rs
9b90bfd68b50f3047ec1ee6e01245efe98311a11
[rust.git] / src / libstd / sync / condvar.rs
1 use crate::fmt;
2 use crate::sync::atomic::{AtomicUsize, Ordering};
3 use crate::sync::{mutex, MutexGuard, PoisonError};
4 use crate::sys_common::condvar as sys;
5 use crate::sys_common::mutex as sys_mutex;
6 use crate::sys_common::poison::{self, LockResult};
7 use crate::time::{Duration, Instant};
8
9 /// A type indicating whether a timed wait on a condition variable returned
10 /// due to a time out or not.
11 ///
12 /// It is returned by the [`wait_timeout`] method.
13 ///
14 /// [`wait_timeout`]: struct.Condvar.html#method.wait_timeout
15 #[derive(Debug, PartialEq, Eq, Copy, Clone)]
16 #[stable(feature = "wait_timeout", since = "1.5.0")]
17 pub struct WaitTimeoutResult(bool);
18
19 impl WaitTimeoutResult {
20     /// Returns `true` if the wait was known to have timed out.
21     ///
22     /// # Examples
23     ///
24     /// This example spawns a thread which will update the boolean value and
25     /// then wait 100 milliseconds before notifying the condvar.
26     ///
27     /// The main thread will wait with a timeout on the condvar and then leave
28     /// once the boolean has been updated and notified.
29     ///
30     /// ```
31     /// use std::sync::{Arc, Condvar, Mutex};
32     /// use std::thread;
33     /// use std::time::Duration;
34     ///
35     /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
36     /// let pair2 = pair.clone();
37     ///
38     /// thread::spawn(move || {
39     ///     let (lock, cvar) = &*pair2;
40     ///
41     ///     // Let's wait 20 milliseconds before notifying the condvar.
42     ///     thread::sleep(Duration::from_millis(20));
43     ///
44     ///     let mut started = lock.lock().unwrap();
45     ///     // We update the boolean value.
46     ///     *started = true;
47     ///     cvar.notify_one();
48     /// });
49     ///
50     /// // Wait for the thread to start up.
51     /// let (lock, cvar) = &*pair;
52     /// let mut started = lock.lock().unwrap();
53     /// loop {
54     ///     // Let's put a timeout on the condvar's wait.
55     ///     let result = cvar.wait_timeout(started, Duration::from_millis(10)).unwrap();
56     ///     // 10 milliseconds have passed, or maybe the value changed!
57     ///     started = result.0;
58     ///     if *started == true {
59     ///         // We received the notification and the value has been updated, we can leave.
60     ///         break
61     ///     }
62     /// }
63     /// ```
64     #[stable(feature = "wait_timeout", since = "1.5.0")]
65     pub fn timed_out(&self) -> bool {
66         self.0
67     }
68 }
69
70 /// A Condition Variable
71 ///
72 /// Condition variables represent the ability to block a thread such that it
73 /// consumes no CPU time while waiting for an event to occur. Condition
74 /// variables are typically associated with a boolean predicate (a condition)
75 /// and a mutex. The predicate is always verified inside of the mutex before
76 /// determining that a thread must block.
77 ///
78 /// Functions in this module will block the current **thread** of execution and
79 /// are bindings to system-provided condition variables where possible. Note
80 /// that this module places one additional restriction over the system condition
81 /// variables: each condvar can be used with precisely one mutex at runtime. Any
82 /// attempt to use multiple mutexes on the same condition variable will result
83 /// in a runtime panic. If this is not desired, then the unsafe primitives in
84 /// `sys` do not have this restriction but may result in undefined behavior.
85 ///
86 /// # Examples
87 ///
88 /// ```
89 /// use std::sync::{Arc, Mutex, Condvar};
90 /// use std::thread;
91 ///
92 /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
93 /// let pair2 = pair.clone();
94 ///
95 /// // Inside of our lock, spawn a new thread, and then wait for it to start.
96 /// thread::spawn(move|| {
97 ///     let (lock, cvar) = &*pair2;
98 ///     let mut started = lock.lock().unwrap();
99 ///     *started = true;
100 ///     // We notify the condvar that the value has changed.
101 ///     cvar.notify_one();
102 /// });
103 ///
104 /// // Wait for the thread to start up.
105 /// let (lock, cvar) = &*pair;
106 /// let mut started = lock.lock().unwrap();
107 /// while !*started {
108 ///     started = cvar.wait(started).unwrap();
109 /// }
110 /// ```
111 #[stable(feature = "rust1", since = "1.0.0")]
112 pub struct Condvar {
113     inner: Box<sys::Condvar>,
114     mutex: AtomicUsize,
115 }
116
117 impl Condvar {
118     /// Creates a new condition variable which is ready to be waited on and
119     /// notified.
120     ///
121     /// # Examples
122     ///
123     /// ```
124     /// use std::sync::Condvar;
125     ///
126     /// let condvar = Condvar::new();
127     /// ```
128     #[stable(feature = "rust1", since = "1.0.0")]
129     pub fn new() -> Condvar {
130         let mut c = Condvar { inner: box sys::Condvar::new(), mutex: AtomicUsize::new(0) };
131         unsafe {
132             c.inner.init();
133         }
134         c
135     }
136
137     /// Blocks the current thread until this condition variable receives a
138     /// notification.
139     ///
140     /// This function will atomically unlock the mutex specified (represented by
141     /// `guard`) and block the current thread. This means that any calls
142     /// to [`notify_one`] or [`notify_all`] which happen logically after the
143     /// mutex is unlocked are candidates to wake this thread up. When this
144     /// function call returns, the lock specified will have been re-acquired.
145     ///
146     /// Note that this function is susceptible to spurious wakeups. Condition
147     /// variables normally have a boolean predicate associated with them, and
148     /// the predicate must always be checked each time this function returns to
149     /// protect against spurious wakeups.
150     ///
151     /// # Errors
152     ///
153     /// This function will return an error if the mutex being waited on is
154     /// poisoned when this thread re-acquires the lock. For more information,
155     /// see information about [poisoning] on the [`Mutex`] type.
156     ///
157     /// # Panics
158     ///
159     /// This function will [`panic!`] if it is used with more than one mutex
160     /// over time. Each condition variable is dynamically bound to exactly one
161     /// mutex to ensure defined behavior across platforms. If this functionality
162     /// is not desired, then unsafe primitives in `sys` are provided.
163     ///
164     /// [`notify_one`]: #method.notify_one
165     /// [`notify_all`]: #method.notify_all
166     /// [poisoning]: ../sync/struct.Mutex.html#poisoning
167     /// [`Mutex`]: ../sync/struct.Mutex.html
168     /// [`panic!`]: ../../std/macro.panic.html
169     ///
170     /// # Examples
171     ///
172     /// ```
173     /// use std::sync::{Arc, Mutex, Condvar};
174     /// use std::thread;
175     ///
176     /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
177     /// let pair2 = pair.clone();
178     ///
179     /// thread::spawn(move|| {
180     ///     let (lock, cvar) = &*pair2;
181     ///     let mut started = lock.lock().unwrap();
182     ///     *started = true;
183     ///     // We notify the condvar that the value has changed.
184     ///     cvar.notify_one();
185     /// });
186     ///
187     /// // Wait for the thread to start up.
188     /// let (lock, cvar) = &*pair;
189     /// let mut started = lock.lock().unwrap();
190     /// // As long as the value inside the `Mutex<bool>` is `false`, we wait.
191     /// while !*started {
192     ///     started = cvar.wait(started).unwrap();
193     /// }
194     /// ```
195     #[stable(feature = "rust1", since = "1.0.0")]
196     pub fn wait<'a, T>(&self, guard: MutexGuard<'a, T>) -> LockResult<MutexGuard<'a, T>> {
197         let poisoned = unsafe {
198             let lock = mutex::guard_lock(&guard);
199             self.verify(lock);
200             self.inner.wait(lock);
201             mutex::guard_poison(&guard).get()
202         };
203         if poisoned { Err(PoisonError::new(guard)) } else { Ok(guard) }
204     }
205
206     /// Blocks the current thread until this condition variable receives a
207     /// notification and the provided condition is false.
208     ///
209     /// This function will atomically unlock the mutex specified (represented by
210     /// `guard`) and block the current thread. This means that any calls
211     /// to [`notify_one`] or [`notify_all`] which happen logically after the
212     /// mutex is unlocked are candidates to wake this thread up. When this
213     /// function call returns, the lock specified will have been re-acquired.
214     ///
215     /// # Errors
216     ///
217     /// This function will return an error if the mutex being waited on is
218     /// poisoned when this thread re-acquires the lock. For more information,
219     /// see information about [poisoning] on the [`Mutex`] type.
220     ///
221     /// [`notify_one`]: #method.notify_one
222     /// [`notify_all`]: #method.notify_all
223     /// [poisoning]: ../sync/struct.Mutex.html#poisoning
224     /// [`Mutex`]: ../sync/struct.Mutex.html
225     ///
226     /// # Examples
227     ///
228     /// ```
229     /// use std::sync::{Arc, Mutex, Condvar};
230     /// use std::thread;
231     ///
232     /// let pair = Arc::new((Mutex::new(true), Condvar::new()));
233     /// let pair2 = pair.clone();
234     ///
235     /// thread::spawn(move|| {
236     ///     let (lock, cvar) = &*pair2;
237     ///     let mut pending = lock.lock().unwrap();
238     ///     *pending = false;
239     ///     // We notify the condvar that the value has changed.
240     ///     cvar.notify_one();
241     /// });
242     ///
243     /// // Wait for the thread to start up.
244     /// let (lock, cvar) = &*pair;
245     /// // As long as the value inside the `Mutex<bool>` is `true`, we wait.
246     /// let _guard = cvar.wait_while(lock.lock().unwrap(), |pending| { *pending }).unwrap();
247     /// ```
248     #[stable(feature = "wait_until", since = "1.42.0")]
249     pub fn wait_while<'a, T, F>(
250         &self,
251         mut guard: MutexGuard<'a, T>,
252         mut condition: F,
253     ) -> LockResult<MutexGuard<'a, T>>
254     where
255         F: FnMut(&mut T) -> bool,
256     {
257         while condition(&mut *guard) {
258             guard = self.wait(guard)?;
259         }
260         Ok(guard)
261     }
262
263     /// Waits on this condition variable for a notification, timing out after a
264     /// specified duration.
265     ///
266     /// The semantics of this function are equivalent to [`wait`]
267     /// except that the thread will be blocked for roughly no longer
268     /// than `ms` milliseconds. This method should not be used for
269     /// precise timing due to anomalies such as preemption or platform
270     /// differences that may not cause the maximum amount of time
271     /// waited to be precisely `ms`.
272     ///
273     /// Note that the best effort is made to ensure that the time waited is
274     /// measured with a monotonic clock, and not affected by the changes made to
275     /// the system time.
276     ///
277     /// The returned boolean is `false` only if the timeout is known
278     /// to have elapsed.
279     ///
280     /// Like [`wait`], the lock specified will be re-acquired when this function
281     /// returns, regardless of whether the timeout elapsed or not.
282     ///
283     /// [`wait`]: #method.wait
284     ///
285     /// # Examples
286     ///
287     /// ```
288     /// use std::sync::{Arc, Mutex, Condvar};
289     /// use std::thread;
290     ///
291     /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
292     /// let pair2 = pair.clone();
293     ///
294     /// thread::spawn(move|| {
295     ///     let (lock, cvar) = &*pair2;
296     ///     let mut started = lock.lock().unwrap();
297     ///     *started = true;
298     ///     // We notify the condvar that the value has changed.
299     ///     cvar.notify_one();
300     /// });
301     ///
302     /// // Wait for the thread to start up.
303     /// let (lock, cvar) = &*pair;
304     /// let mut started = lock.lock().unwrap();
305     /// // As long as the value inside the `Mutex<bool>` is `false`, we wait.
306     /// loop {
307     ///     let result = cvar.wait_timeout_ms(started, 10).unwrap();
308     ///     // 10 milliseconds have passed, or maybe the value changed!
309     ///     started = result.0;
310     ///     if *started == true {
311     ///         // We received the notification and the value has been updated, we can leave.
312     ///         break
313     ///     }
314     /// }
315     /// ```
316     #[stable(feature = "rust1", since = "1.0.0")]
317     #[rustc_deprecated(since = "1.6.0", reason = "replaced by `std::sync::Condvar::wait_timeout`")]
318     pub fn wait_timeout_ms<'a, T>(
319         &self,
320         guard: MutexGuard<'a, T>,
321         ms: u32,
322     ) -> LockResult<(MutexGuard<'a, T>, bool)> {
323         let res = self.wait_timeout(guard, Duration::from_millis(ms as u64));
324         poison::map_result(res, |(a, b)| (a, !b.timed_out()))
325     }
326
327     /// Waits on this condition variable for a notification, timing out after a
328     /// specified duration.
329     ///
330     /// The semantics of this function are equivalent to [`wait`] except that
331     /// the thread will be blocked for roughly no longer than `dur`. This
332     /// method should not be used for precise timing due to anomalies such as
333     /// preemption or platform differences that may not cause the maximum
334     /// amount of time waited to be precisely `dur`.
335     ///
336     /// Note that the best effort is made to ensure that the time waited is
337     /// measured with a monotonic clock, and not affected by the changes made to
338     /// the system time. This function is susceptible to spurious wakeups.
339     /// Condition variables normally have a boolean predicate associated with
340     /// them, and the predicate must always be checked each time this function
341     /// returns to protect against spurious wakeups. Additionally, it is
342     /// typically desirable for the timeout to not exceed some duration in
343     /// spite of spurious wakes, thus the sleep-duration is decremented by the
344     /// amount slept. Alternatively, use the `wait_timeout_while` method
345     /// to wait with a timeout while a predicate is true.
346     ///
347     /// The returned [`WaitTimeoutResult`] value indicates if the timeout is
348     /// known to have elapsed.
349     ///
350     /// Like [`wait`], the lock specified will be re-acquired when this function
351     /// returns, regardless of whether the timeout elapsed or not.
352     ///
353     /// [`wait`]: #method.wait
354     /// [`wait_timeout_while`]: #method.wait_timeout_while
355     /// [`WaitTimeoutResult`]: struct.WaitTimeoutResult.html
356     ///
357     /// # Examples
358     ///
359     /// ```
360     /// use std::sync::{Arc, Mutex, Condvar};
361     /// use std::thread;
362     /// use std::time::Duration;
363     ///
364     /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
365     /// let pair2 = pair.clone();
366     ///
367     /// thread::spawn(move|| {
368     ///     let (lock, cvar) = &*pair2;
369     ///     let mut started = lock.lock().unwrap();
370     ///     *started = true;
371     ///     // We notify the condvar that the value has changed.
372     ///     cvar.notify_one();
373     /// });
374     ///
375     /// // wait for the thread to start up
376     /// let (lock, cvar) = &*pair;
377     /// let mut started = lock.lock().unwrap();
378     /// // as long as the value inside the `Mutex<bool>` is `false`, we wait
379     /// loop {
380     ///     let result = cvar.wait_timeout(started, Duration::from_millis(10)).unwrap();
381     ///     // 10 milliseconds have passed, or maybe the value changed!
382     ///     started = result.0;
383     ///     if *started == true {
384     ///         // We received the notification and the value has been updated, we can leave.
385     ///         break
386     ///     }
387     /// }
388     /// ```
389     #[stable(feature = "wait_timeout", since = "1.5.0")]
390     pub fn wait_timeout<'a, T>(
391         &self,
392         guard: MutexGuard<'a, T>,
393         dur: Duration,
394     ) -> LockResult<(MutexGuard<'a, T>, WaitTimeoutResult)> {
395         let (poisoned, result) = unsafe {
396             let lock = mutex::guard_lock(&guard);
397             self.verify(lock);
398             let success = self.inner.wait_timeout(lock, dur);
399             (mutex::guard_poison(&guard).get(), WaitTimeoutResult(!success))
400         };
401         if poisoned { Err(PoisonError::new((guard, result))) } else { Ok((guard, result)) }
402     }
403
404     /// Waits on this condition variable for a notification, timing out after a
405     /// specified duration.
406     ///
407     /// The semantics of this function are equivalent to [`wait_while`] except
408     /// that the thread will be blocked for roughly no longer than `dur`. This
409     /// method should not be used for precise timing due to anomalies such as
410     /// preemption or platform differences that may not cause the maximum
411     /// amount of time waited to be precisely `dur`.
412     ///
413     /// Note that the best effort is made to ensure that the time waited is
414     /// measured with a monotonic clock, and not affected by the changes made to
415     /// the system time.
416     ///
417     /// The returned [`WaitTimeoutResult`] value indicates if the timeout is
418     /// known to have elapsed without the condition being met.
419     ///
420     /// Like [`wait_while`], the lock specified will be re-acquired when this
421     /// function returns, regardless of whether the timeout elapsed or not.
422     ///
423     /// [`wait_while`]: #method.wait_while
424     /// [`wait_timeout`]: #method.wait_timeout
425     /// [`WaitTimeoutResult`]: struct.WaitTimeoutResult.html
426     ///
427     /// # Examples
428     ///
429     /// ```
430     /// use std::sync::{Arc, Mutex, Condvar};
431     /// use std::thread;
432     /// use std::time::Duration;
433     ///
434     /// let pair = Arc::new((Mutex::new(true), Condvar::new()));
435     /// let pair2 = pair.clone();
436     ///
437     /// thread::spawn(move|| {
438     ///     let (lock, cvar) = &*pair2;
439     ///     let mut pending = lock.lock().unwrap();
440     ///     *pending = false;
441     ///     // We notify the condvar that the value has changed.
442     ///     cvar.notify_one();
443     /// });
444     ///
445     /// // wait for the thread to start up
446     /// let (lock, cvar) = &*pair;
447     /// let result = cvar.wait_timeout_while(
448     ///     lock.lock().unwrap(),
449     ///     Duration::from_millis(100),
450     ///     |&mut pending| pending,
451     /// ).unwrap();
452     /// if result.1.timed_out() {
453     ///     // timed-out without the condition ever evaluating to false.
454     /// }
455     /// // access the locked mutex via result.0
456     /// ```
457     #[stable(feature = "wait_timeout_until", since = "1.42.0")]
458     pub fn wait_timeout_while<'a, T, F>(
459         &self,
460         mut guard: MutexGuard<'a, T>,
461         dur: Duration,
462         mut condition: F,
463     ) -> LockResult<(MutexGuard<'a, T>, WaitTimeoutResult)>
464     where
465         F: FnMut(&mut T) -> bool,
466     {
467         let start = Instant::now();
468         loop {
469             if !condition(&mut *guard) {
470                 return Ok((guard, WaitTimeoutResult(false)));
471             }
472             let timeout = match dur.checked_sub(start.elapsed()) {
473                 Some(timeout) => timeout,
474                 None => return Ok((guard, WaitTimeoutResult(true))),
475             };
476             guard = self.wait_timeout(guard, timeout)?.0;
477         }
478     }
479
480     /// Wakes up one blocked thread on this condvar.
481     ///
482     /// If there is a blocked thread on this condition variable, then it will
483     /// be woken up from its call to [`wait`] or [`wait_timeout`]. Calls to
484     /// `notify_one` are not buffered in any way.
485     ///
486     /// To wake up all threads, see [`notify_all`].
487     ///
488     /// [`wait`]: #method.wait
489     /// [`wait_timeout`]: #method.wait_timeout
490     /// [`notify_all`]: #method.notify_all
491     ///
492     /// # Examples
493     ///
494     /// ```
495     /// use std::sync::{Arc, Mutex, Condvar};
496     /// use std::thread;
497     ///
498     /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
499     /// let pair2 = pair.clone();
500     ///
501     /// thread::spawn(move|| {
502     ///     let (lock, cvar) = &*pair2;
503     ///     let mut started = lock.lock().unwrap();
504     ///     *started = true;
505     ///     // We notify the condvar that the value has changed.
506     ///     cvar.notify_one();
507     /// });
508     ///
509     /// // Wait for the thread to start up.
510     /// let (lock, cvar) = &*pair;
511     /// let mut started = lock.lock().unwrap();
512     /// // As long as the value inside the `Mutex<bool>` is `false`, we wait.
513     /// while !*started {
514     ///     started = cvar.wait(started).unwrap();
515     /// }
516     /// ```
517     #[stable(feature = "rust1", since = "1.0.0")]
518     pub fn notify_one(&self) {
519         unsafe { self.inner.notify_one() }
520     }
521
522     /// Wakes up all blocked threads on this condvar.
523     ///
524     /// This method will ensure that any current waiters on the condition
525     /// variable are awoken. Calls to `notify_all()` are not buffered in any
526     /// way.
527     ///
528     /// To wake up only one thread, see [`notify_one`].
529     ///
530     /// [`notify_one`]: #method.notify_one
531     ///
532     /// # Examples
533     ///
534     /// ```
535     /// use std::sync::{Arc, Mutex, Condvar};
536     /// use std::thread;
537     ///
538     /// let pair = Arc::new((Mutex::new(false), Condvar::new()));
539     /// let pair2 = pair.clone();
540     ///
541     /// thread::spawn(move|| {
542     ///     let (lock, cvar) = &*pair2;
543     ///     let mut started = lock.lock().unwrap();
544     ///     *started = true;
545     ///     // We notify the condvar that the value has changed.
546     ///     cvar.notify_all();
547     /// });
548     ///
549     /// // Wait for the thread to start up.
550     /// let (lock, cvar) = &*pair;
551     /// let mut started = lock.lock().unwrap();
552     /// // As long as the value inside the `Mutex<bool>` is `false`, we wait.
553     /// while !*started {
554     ///     started = cvar.wait(started).unwrap();
555     /// }
556     /// ```
557     #[stable(feature = "rust1", since = "1.0.0")]
558     pub fn notify_all(&self) {
559         unsafe { self.inner.notify_all() }
560     }
561
562     fn verify(&self, mutex: &sys_mutex::Mutex) {
563         let addr = mutex as *const _ as usize;
564         match self.mutex.compare_and_swap(0, addr, Ordering::SeqCst) {
565             // If we got out 0, then we have successfully bound the mutex to
566             // this cvar.
567             0 => {}
568
569             // If we get out a value that's the same as `addr`, then someone
570             // already beat us to the punch.
571             n if n == addr => {}
572
573             // Anything else and we're using more than one mutex on this cvar,
574             // which is currently disallowed.
575             _ => panic!(
576                 "attempted to use a condition variable with two \
577                          mutexes"
578             ),
579         }
580     }
581 }
582
583 #[stable(feature = "std_debug", since = "1.16.0")]
584 impl fmt::Debug for Condvar {
585     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
586         f.pad("Condvar { .. }")
587     }
588 }
589
590 #[stable(feature = "condvar_default", since = "1.10.0")]
591 impl Default for Condvar {
592     /// Creates a `Condvar` which is ready to be waited on and notified.
593     fn default() -> Condvar {
594         Condvar::new()
595     }
596 }
597
598 #[stable(feature = "rust1", since = "1.0.0")]
599 impl Drop for Condvar {
600     fn drop(&mut self) {
601         unsafe { self.inner.destroy() }
602     }
603 }
604
605 #[cfg(test)]
606 mod tests {
607     use crate::sync::atomic::{AtomicBool, Ordering};
608     use crate::sync::mpsc::channel;
609     use crate::sync::{Arc, Condvar, Mutex};
610     use crate::thread;
611     use crate::time::Duration;
612
613     #[test]
614     fn smoke() {
615         let c = Condvar::new();
616         c.notify_one();
617         c.notify_all();
618     }
619
620     #[test]
621     #[cfg_attr(target_os = "emscripten", ignore)]
622     fn notify_one() {
623         let m = Arc::new(Mutex::new(()));
624         let m2 = m.clone();
625         let c = Arc::new(Condvar::new());
626         let c2 = c.clone();
627
628         let g = m.lock().unwrap();
629         let _t = thread::spawn(move || {
630             let _g = m2.lock().unwrap();
631             c2.notify_one();
632         });
633         let g = c.wait(g).unwrap();
634         drop(g);
635     }
636
637     #[test]
638     #[cfg_attr(target_os = "emscripten", ignore)]
639     fn notify_all() {
640         const N: usize = 10;
641
642         let data = Arc::new((Mutex::new(0), Condvar::new()));
643         let (tx, rx) = channel();
644         for _ in 0..N {
645             let data = data.clone();
646             let tx = tx.clone();
647             thread::spawn(move || {
648                 let &(ref lock, ref cond) = &*data;
649                 let mut cnt = lock.lock().unwrap();
650                 *cnt += 1;
651                 if *cnt == N {
652                     tx.send(()).unwrap();
653                 }
654                 while *cnt != 0 {
655                     cnt = cond.wait(cnt).unwrap();
656                 }
657                 tx.send(()).unwrap();
658             });
659         }
660         drop(tx);
661
662         let &(ref lock, ref cond) = &*data;
663         rx.recv().unwrap();
664         let mut cnt = lock.lock().unwrap();
665         *cnt = 0;
666         cond.notify_all();
667         drop(cnt);
668
669         for _ in 0..N {
670             rx.recv().unwrap();
671         }
672     }
673
674     #[test]
675     #[cfg_attr(target_os = "emscripten", ignore)]
676     fn wait_while() {
677         let pair = Arc::new((Mutex::new(false), Condvar::new()));
678         let pair2 = pair.clone();
679
680         // Inside of our lock, spawn a new thread, and then wait for it to start.
681         thread::spawn(move || {
682             let &(ref lock, ref cvar) = &*pair2;
683             let mut started = lock.lock().unwrap();
684             *started = true;
685             // We notify the condvar that the value has changed.
686             cvar.notify_one();
687         });
688
689         // Wait for the thread to start up.
690         let &(ref lock, ref cvar) = &*pair;
691         let guard = cvar.wait_while(lock.lock().unwrap(), |started| !*started);
692         assert!(*guard.unwrap());
693     }
694
695     #[test]
696     #[cfg_attr(target_os = "emscripten", ignore)]
697     fn wait_timeout_wait() {
698         let m = Arc::new(Mutex::new(()));
699         let c = Arc::new(Condvar::new());
700
701         loop {
702             let g = m.lock().unwrap();
703             let (_g, no_timeout) = c.wait_timeout(g, Duration::from_millis(1)).unwrap();
704             // spurious wakeups mean this isn't necessarily true
705             // so execute test again, if not timeout
706             if !no_timeout.timed_out() {
707                 continue;
708             }
709
710             break;
711         }
712     }
713
714     #[test]
715     #[cfg_attr(target_os = "emscripten", ignore)]
716     fn wait_timeout_while_wait() {
717         let m = Arc::new(Mutex::new(()));
718         let c = Arc::new(Condvar::new());
719
720         let g = m.lock().unwrap();
721         let (_g, wait) = c.wait_timeout_while(g, Duration::from_millis(1), |_| true).unwrap();
722         // no spurious wakeups. ensure it timed-out
723         assert!(wait.timed_out());
724     }
725
726     #[test]
727     #[cfg_attr(target_os = "emscripten", ignore)]
728     fn wait_timeout_while_instant_satisfy() {
729         let m = Arc::new(Mutex::new(()));
730         let c = Arc::new(Condvar::new());
731
732         let g = m.lock().unwrap();
733         let (_g, wait) = c.wait_timeout_while(g, Duration::from_millis(0), |_| false).unwrap();
734         // ensure it didn't time-out even if we were not given any time.
735         assert!(!wait.timed_out());
736     }
737
738     #[test]
739     #[cfg_attr(target_os = "emscripten", ignore)]
740     fn wait_timeout_while_wake() {
741         let pair = Arc::new((Mutex::new(false), Condvar::new()));
742         let pair_copy = pair.clone();
743
744         let &(ref m, ref c) = &*pair;
745         let g = m.lock().unwrap();
746         let _t = thread::spawn(move || {
747             let &(ref lock, ref cvar) = &*pair_copy;
748             let mut started = lock.lock().unwrap();
749             thread::sleep(Duration::from_millis(1));
750             *started = true;
751             cvar.notify_one();
752         });
753         let (g2, wait) = c
754             .wait_timeout_while(g, Duration::from_millis(u64::MAX), |&mut notified| !notified)
755             .unwrap();
756         // ensure it didn't time-out even if we were not given any time.
757         assert!(!wait.timed_out());
758         assert!(*g2);
759     }
760
761     #[test]
762     #[cfg_attr(target_os = "emscripten", ignore)]
763     fn wait_timeout_wake() {
764         let m = Arc::new(Mutex::new(()));
765         let c = Arc::new(Condvar::new());
766
767         loop {
768             let g = m.lock().unwrap();
769
770             let c2 = c.clone();
771             let m2 = m.clone();
772
773             let notified = Arc::new(AtomicBool::new(false));
774             let notified_copy = notified.clone();
775
776             let t = thread::spawn(move || {
777                 let _g = m2.lock().unwrap();
778                 thread::sleep(Duration::from_millis(1));
779                 notified_copy.store(true, Ordering::SeqCst);
780                 c2.notify_one();
781             });
782             let (g, timeout_res) = c.wait_timeout(g, Duration::from_millis(u64::MAX)).unwrap();
783             assert!(!timeout_res.timed_out());
784             // spurious wakeups mean this isn't necessarily true
785             // so execute test again, if not notified
786             if !notified.load(Ordering::SeqCst) {
787                 t.join().unwrap();
788                 continue;
789             }
790             drop(g);
791
792             t.join().unwrap();
793
794             break;
795         }
796     }
797
798     #[test]
799     #[should_panic]
800     #[cfg_attr(target_os = "emscripten", ignore)]
801     fn two_mutexes() {
802         let m = Arc::new(Mutex::new(()));
803         let m2 = m.clone();
804         let c = Arc::new(Condvar::new());
805         let c2 = c.clone();
806
807         let mut g = m.lock().unwrap();
808         let _t = thread::spawn(move || {
809             let _g = m2.lock().unwrap();
810             c2.notify_one();
811         });
812         g = c.wait(g).unwrap();
813         drop(g);
814
815         let m = Mutex::new(());
816         let _ = c.wait(m.lock().unwrap()).unwrap();
817     }
818 }