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
use arraydeque::ArrayDeque;

use crate::interrupts::guard::GUARD;

use super::{Scheduler, APPS};

/// Semaphore used for synchronization of threads.
///
/// The class Semaphore implements the concept of counting semaphores.
#[derive(Debug)]
pub struct Semaphore {
    counter: usize,
    waiting: ArrayDeque<usize, APPS>,
}

impl Semaphore {
    // Initialize the `counter` with provided value
    pub const fn new(counter: usize) -> Self {
        Self {
            counter,
            waiting: ArrayDeque::new(),
        }
    }
    /// Wait for access to the critical area
    pub fn wait(&mut self, scheduler: &mut Scheduler) {
        if let Some(c) = self.counter.checked_sub(1) {
            self.counter = c;
        } else {
            let tid = scheduler.active().expect("No running threads");
            self.waiting.push_back(tid).unwrap();
            scheduler.resume(false);
        }
    }
    /// Leave the critical area
    pub fn signal(&mut self, scheduler: &mut Scheduler) {
        if let Some(thread) = self.waiting.pop_front() {
            scheduler.ready(thread);
        } else {
            self.counter += 1;
        }
    }
}
impl Drop for Semaphore {
    fn drop(&mut self) {
        while let Some(thread) = self.waiting.pop_front() {
            unsafe { GUARD.get().scheduler.ready(thread) }
        }
    }
}