1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
use crate::mutex::{Mutex, SpinLock};
use crate::semaphore::{ReadoutSemaphore, Semaphore, TimeoutSemaphore, TrySemaphore};
use crate::{ThreadFunctions, ThreadParker, ThreadTimeoutParker, TimeFunctions};
use alloc::collections::VecDeque;
use alloc::sync::Arc;
use core::fmt::Debug;
use core::ops::{AddAssign, SubAssign};
use core::sync::atomic::{AtomicBool, Ordering};
use core::time::Duration;
use num::{One, Zero};

/// A semaphore based on thread parking
#[derive(Debug)]
pub struct ParkSemaphore<C, CS>
where
    CS: ThreadParker,
{
    inner: SpinLock<ParkSemaphoreInner<C, CS>, CS>,
}
impl<C, CS> ParkSemaphore<C, CS>
where
    CS: ThreadParker,
{
    /// Creates a new [`ParkSemaphore`] from a `start_count`.
    pub fn new(start_count: C) -> Self {
        Self {
            inner: SpinLock::new(ParkSemaphoreInner {
                count: start_count,
                parkers: Default::default(),
            }),
        }
    }
}
impl<C, CS> Default for ParkSemaphore<C, CS>
where
    C: Zero,
    CS: ThreadParker,
{
    fn default() -> Self {
        Self::new(C::zero())
    }
}
unsafe impl<C, CS> TrySemaphore for ParkSemaphore<C, CS>
where
    C: Zero + One + AddAssign + SubAssign,
    CS: ThreadParker + ThreadFunctions,
{
    fn try_wait(&self) -> bool {
        let mut guard = self.inner.lock();
        if guard.count.is_zero() {
            false
        } else {
            guard.count -= C::one();
            true
        }
    }

    fn signal(&self) {
        let mut guard = self.inner.lock();
        if guard.count.is_zero() {
            if let Some((thread_id, should_wake)) = guard.parkers.pop_front() {
                should_wake.store(true, Ordering::Release);
                CS::unpark(thread_id);
                return;
            }
        }
        guard.count += C::one();
    }
}
unsafe impl<C, CS> Semaphore for ParkSemaphore<C, CS>
where
    C: Zero + One + AddAssign + SubAssign,
    CS: ThreadParker + ThreadFunctions,
{
    fn wait(&self) {
        let mut guard = self.inner.lock();
        if !guard.count.is_zero() {
            guard.count -= C::one();
            return;
        }
        let should_wake = Arc::new(AtomicBool::new(false));
        guard
            .parkers
            .push_back((CS::current_thread(), should_wake.clone()));
        drop(guard);
        loop {
            if should_wake.load(Ordering::Acquire) {
                break;
            }
            CS::park();
        }
    }
}
unsafe impl<C, CS> TimeoutSemaphore for ParkSemaphore<C, CS>
where
    C: Zero + One + AddAssign + SubAssign,
    CS: ThreadTimeoutParker + TimeFunctions + ThreadFunctions,
{
    fn wait_timeout(&self, timeout: Duration) -> bool {
        let mut guard = self.inner.lock();
        if !guard.count.is_zero() {
            guard.count -= C::one();
            return true;
        }
        let should_wake = Arc::new(AtomicBool::new(false));
        guard
            .parkers
            .push_back((CS::current_thread(), should_wake.clone()));
        drop(guard);
        let end = CS::current_time() + timeout;
        loop {
            if CS::current_time() >= end {
                return false;
            }
            if should_wake.load(Ordering::Acquire) {
                return true;
            }
            CS::park_timeout(end - CS::current_time());
        }
    }
}
impl<C, CS> ReadoutSemaphore for ParkSemaphore<C, CS>
where
    C: Zero + One + AddAssign + SubAssign + Copy,
    CS: ThreadParker + ThreadFunctions,
{
    type Count = C;

    fn count(&self) -> Self::Count {
        self.inner.lock().count
    }
}

#[derive(Debug)]
struct ParkSemaphoreInner<C, CS>
where
    CS: ThreadParker,
{
    count: C,
    parkers: VecDeque<(CS::ThreadId, Arc<AtomicBool>)>,
}