|
| 1 | +use crate::sync::atomic::Ordering::Relaxed; |
| 2 | +use crate::sys::futex::{Futex, futex_requeue, futex_wait, futex_wake}; |
| 3 | +use crate::sys::sync::Mutex; |
| 4 | +use crate::time::Duration; |
| 5 | + |
| 6 | +pub struct Condvar { |
| 7 | + // The value of this atomic is simply incremented on every notification. |
| 8 | + // This is used by `.wait()` to not miss any notifications after |
| 9 | + // unlocking the mutex and before waiting for notifications. |
| 10 | + futex: Futex, |
| 11 | + // The futex to requeue to. |
| 12 | + // Its value is simply incremented when a waiter has been woken and acquired mutex. |
| 13 | + futex2: Futex, |
| 14 | +} |
| 15 | + |
| 16 | +impl Condvar { |
| 17 | + #[inline] |
| 18 | + pub const fn new() -> Self { |
| 19 | + Self { futex: Futex::new(0), futex2: Futex::new(0) } |
| 20 | + } |
| 21 | + |
| 22 | + // All the memory orderings here are `Relaxed`, |
| 23 | + // because synchronization is done by unlocking and locking the mutex. |
| 24 | + |
| 25 | + pub fn notify_one(&self) { |
| 26 | + self.futex.fetch_add(1, Relaxed); |
| 27 | + futex_wake(&self.futex); |
| 28 | + } |
| 29 | + |
| 30 | + pub fn notify_all(&self) { |
| 31 | + self.futex.fetch_add(1, Relaxed); |
| 32 | + futex_requeue(&self.futex, &self.futex2); |
| 33 | + } |
| 34 | + |
| 35 | + pub unsafe fn wait(&self, mutex: &Mutex) { |
| 36 | + self.wait_optional_timeout(mutex, None); |
| 37 | + } |
| 38 | + |
| 39 | + pub unsafe fn wait_timeout(&self, mutex: &Mutex, timeout: Duration) -> bool { |
| 40 | + self.wait_optional_timeout(mutex, Some(timeout)) |
| 41 | + } |
| 42 | + |
| 43 | + unsafe fn wait_optional_timeout(&self, mutex: &Mutex, timeout: Option<Duration>) -> bool { |
| 44 | + // Examine the notification counter _before_ we unlock the mutex. |
| 45 | + let futex_value = self.futex.load(Relaxed); |
| 46 | + |
| 47 | + // Unlock the mutex before going to sleep. |
| 48 | + mutex.unlock(); |
| 49 | + |
| 50 | + // Wait, but only if there hasn't been any |
| 51 | + // notification since we unlocked the mutex. |
| 52 | + let r = futex_wait(&self.futex, futex_value, timeout); |
| 53 | + |
| 54 | + // Lock the mutex again. |
| 55 | + mutex.lock(); |
| 56 | + |
| 57 | + // Wake another waiter. |
| 58 | + if r { |
| 59 | + self.futex2.fetch_add(1, Relaxed); |
| 60 | + futex_wake(&self.futex2); |
| 61 | + } |
| 62 | + |
| 63 | + r |
| 64 | + } |
| 65 | +} |
0 commit comments