wasmer_wasix/syscalls/wasix/
thread_sleep.rs

1use std::task::Waker;
2
3use super::*;
4use crate::syscalls::*;
5
6/// ### `thread_sleep()`
7/// Sends the current thread to sleep for a period of time
8///
9/// ## Parameters
10///
11/// * `duration` - Amount of time that the thread should sleep
12#[instrument(level = "trace", skip_all, fields(%duration), ret)]
13pub fn thread_sleep<M: MemorySize + 'static>(
14    mut ctx: FunctionEnvMut<'_, WasiEnv>,
15    duration: Timestamp,
16) -> Result<Errno, WasiError> {
17    WasiEnv::do_pending_operations(&mut ctx)?;
18
19    thread_sleep_internal::<M>(ctx, duration)
20}
21
22pub(crate) fn thread_sleep_internal<M: MemorySize + 'static>(
23    mut ctx: FunctionEnvMut<'_, WasiEnv>,
24    duration: Timestamp,
25) -> Result<Errno, WasiError> {
26    if let Some(()) = unsafe { handle_rewind::<M, _>(&mut ctx) } {
27        return Ok(Errno::Success);
28    }
29
30    ctx = wasi_try_ok!(maybe_backoff::<M>(ctx)?);
31    ctx = wasi_try_ok!(maybe_snapshot::<M>(ctx)?);
32
33    let env = ctx.data();
34
35    #[cfg(feature = "sys-thread")]
36    if duration == 0 {
37        std::thread::yield_now();
38    }
39
40    if duration > 0 {
41        let duration = Duration::from_nanos(duration);
42        let tasks = env.tasks().clone();
43        let res = __asyncify_with_deep_sleep::<M, _, _>(ctx, async move {
44            tasks.sleep_now(duration).await;
45        })?;
46    }
47    Ok(Errno::Success)
48}