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                continue;
22            }
23            Err(e) => return Err(e.into()),
24        }
25    }
26}
27
28#[cfg(test)]
29mod tests {
30    use core::time::Duration;
31
32    use crate::thread::sleep;
33    use crate::time::MonotonicInstant;
34
35    #[test]
36    fn try_sleep() {
37        let sleep_dur = Duration::from_millis(15);
38        let now = MonotonicInstant::now();
39        sleep(sleep_dur).unwrap();
40        let elapsed = now.elapsed();
41        assert!(elapsed > sleep_dur);
42    }
43}