tiny_std/
thread.rs

1/// We'll need symbols to set up a `panic_handler`, and alloc to run threads.
2/// We also need to set tls, which is done in `start`
3#[cfg(all(feature = "threaded", feature = "symbols"))]
4pub(crate) mod spawn;
5
6use crate::error::Result;
7use core::time::Duration;
8use rusl::error::Errno;
9#[cfg(all(feature = "threaded", feature = "symbols"))]
10pub use spawn::*;
11
12/// Sleep the current thread for the provided `Duration`
13/// # Errors
14/// Errors on a malformed duration, or userspace data copying errors
15pub fn sleep(duration: Duration) -> Result<()> {
16    let mut ts = duration.try_into()?;
17    loop {
18        match rusl::time::nanosleep_same_ptr(&mut ts) {
19            Ok(()) => return Ok(()),
20            Err(ref e) if e.code == Some(Errno::EINTR) => {}
21            Err(e) => return Err(e.into()),
22        }
23    }
24}
25
26#[cfg(test)]
27mod tests {
28    use core::time::Duration;
29
30    use crate::thread::sleep;
31    use crate::time::MonotonicInstant;
32
33    #[test]
34    fn try_sleep() {
35        let sleep_dur = Duration::from_millis(15);
36        let now = MonotonicInstant::now();
37        sleep(sleep_dur).unwrap();
38        let elapsed = now.elapsed();
39        assert!(elapsed > sleep_dur);
40    }
41}