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
use core::cell::UnsafeCell;
use core::mem;
use core::convert::TryFrom;

use error_code::PosixError;

///POSIX implementation of Semaphore
///
///Note: `wait_timeout` returns false on interrupt by signal
pub struct Sem {
    handle: UnsafeCell<libc::sem_t>,
}

impl super::Semaphore for Sem {
    fn new(init: u32) -> Option<Self> {
        let mut handle = mem::MaybeUninit::uninit();

        let res = unsafe {
            libc::sem_init(handle.as_mut_ptr(), 0, init as libc::c_uint)
        };

        match res {
            0 => Some(Self {
                handle: UnsafeCell::new(unsafe {
                    handle.assume_init()
                })
            }),
            _ => None,
        }
    }

    fn wait(&self) {
        loop {
            let res = unsafe {
                libc::sem_wait(self.handle.get())
            };

            if res == -1 {
                let errno = PosixError::last();
                debug_assert_eq!(errno.raw_code(), libc::EINTR, "Unexpected error");
                continue;
            }

            break
        }
    }

    fn try_wait(&self) -> bool {
        loop {
            let res = unsafe {
                libc::sem_trywait(self.handle.get())
            };

            if res == -1 {
                let errno = PosixError::last();
                if errno.is_would_block() {
                    break false;
                }

                debug_assert_eq!(errno.raw_code(), libc::EINTR, "Unexpected error");
                continue;
            }

            break true
        }
    }

    fn wait_timeout(&self, timeout: core::time::Duration) -> bool {
        let timeout = libc::timespec {
            tv_sec: timeout.as_secs() as libc::time_t,
            #[cfg(target_pointer_width = "64")]
            tv_nsec: libc::suseconds_t::from(timeout.subsec_nanos()),
            #[cfg(not(target_pointer_width = "64"))]
            tv_nsec: libc::suseconds_t::try_from(timeout.subsec_nanos()).unwrap_or(libc::suseconds_t::max_value()),
        };

        loop {
            let res = unsafe {
                libc::sem_timedwait(self.handle.get(), &timeout)
            };

            if res == -1 {
                let errno = PosixError::last();
                if errno.is_would_block() || errno.raw_code() == libc::ETIMEDOUT {
                    break false;
                }

                debug_assert_eq!(errno.raw_code(), libc::EINTR, "Unexpected error");
                continue;
            }

            break true
        }
    }

    fn signal(&self) {
        let res = unsafe {
            libc::sem_post(self.handle.get())
        };
        debug_assert_eq!(res, 0);
    }

    fn post(&self) -> bool {
        let mut val = 0;
        unsafe {
            libc::sem_getvalue(self.handle.get(), &mut val);
        }

        self.signal();

        val == 0
    }
}

impl Drop for Sem {
    fn drop(&mut self) {
        unsafe {
            libc::sem_destroy(self.handle.get());
        }
    }
}

unsafe impl Send for Sem {}
unsafe impl Sync for Sem {}