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