about summary refs log tree commit diff
path: root/src/libstd/sys/hermit/condvar.rs
blob: 5b7f16ce562b9b30862071a313618b6f13079df1 (plain)
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
use crate::cmp;
use crate::sys::hermit::abi;
use crate::sys::mutex::Mutex;
use crate::time::Duration;

pub struct Condvar {
    identifier: usize,
}

impl Condvar {
    pub const fn new() -> Condvar {
        Condvar { identifier: 0 }
    }

    #[inline]
    pub unsafe fn init(&mut self) {
        // nothing to do
    }

    pub unsafe fn notify_one(&self) {
        let _ = abi::notify(self.id(), 1);
    }

    #[inline]
    pub unsafe fn notify_all(&self) {
        let _ = abi::notify(self.id(), -1 /* =all */);
    }

    pub unsafe fn wait(&self, mutex: &Mutex) {
        // add current task to the wait queue
        let _ = abi::add_queue(self.id(), -1 /* no timeout */);
        mutex.unlock();
        let _ = abi::wait(self.id());
        mutex.lock();
    }

    pub unsafe fn wait_timeout(&self, mutex: &Mutex, dur: Duration) -> bool {
        let nanos = dur.as_nanos();
        let nanos = cmp::min(i64::max_value() as u128, nanos);

        // add current task to the wait queue
        let _ = abi::add_queue(self.id(), nanos as i64);

        mutex.unlock();
        // If the return value is !0 then a timeout happened, so we return
        // `false` as we weren't actually notified.
        let ret = abi::wait(self.id()) == 0;
        mutex.lock();

        ret
    }

    #[inline]
    pub unsafe fn destroy(&self) {
        let _ = abi::destroy_queue(self.id());
    }

    #[inline]
    fn id(&self) -> usize {
        &self.identifier as *const usize as usize
    }
}