]> git.lizzy.rs Git - rust.git/blob - library/std/src/sys_common/condvar.rs
acd8b69e9ac556d6b885acb89be4e2d79733b376
[rust.git] / library / std / src / sys_common / condvar.rs
1 use crate::sys::condvar as imp;
2 use crate::sys::mutex as mutex_imp;
3 use crate::sys_common::mutex::MovableMutex;
4 use crate::time::Duration;
5
6 mod check;
7
8 type CondvarCheck = <mutex_imp::MovableMutex as check::CondvarCheck>::Check;
9
10 /// An OS-based condition variable.
11 pub struct Condvar {
12     inner: Box<imp::Condvar>,
13     check: CondvarCheck,
14 }
15
16 impl Condvar {
17     /// Creates a new condition variable for use.
18     pub fn new() -> Self {
19         let mut c = box imp::Condvar::new();
20         unsafe { c.init() };
21         Self { inner: c, check: CondvarCheck::new() }
22     }
23
24     /// Signals one waiter on this condition variable to wake up.
25     #[inline]
26     pub fn notify_one(&self) {
27         unsafe { self.inner.notify_one() };
28     }
29
30     /// Awakens all current waiters on this condition variable.
31     #[inline]
32     pub fn notify_all(&self) {
33         unsafe { self.inner.notify_all() };
34     }
35
36     /// Waits for a signal on the specified mutex.
37     ///
38     /// Behavior is undefined if the mutex is not locked by the current thread.
39     ///
40     /// May panic if used with more than one mutex.
41     #[inline]
42     pub unsafe fn wait(&self, mutex: &MovableMutex) {
43         self.check.verify(mutex);
44         self.inner.wait(mutex.raw())
45     }
46
47     /// Waits for a signal on the specified mutex with a timeout duration
48     /// specified by `dur` (a relative time into the future).
49     ///
50     /// Behavior is undefined if the mutex is not locked by the current thread.
51     ///
52     /// May panic if used with more than one mutex.
53     #[inline]
54     pub unsafe fn wait_timeout(&self, mutex: &MovableMutex, dur: Duration) -> bool {
55         self.check.verify(mutex);
56         self.inner.wait_timeout(mutex.raw(), dur)
57     }
58 }
59
60 impl Drop for Condvar {
61     fn drop(&mut self) {
62         unsafe { self.inner.destroy() };
63     }
64 }