oscall 0.1.0

Low-level cross-platform interface to operating system services: files, memory mapping, networking and more, with no libc on Linux
Documentation
//! Waiting on a value in memory, and waking the waiters: the primitive
//! mutexes, condition variables and other locks are built from.
//!
//! A thread calls [`wait`] to sleep for as long as an [`AtomicU32`] holds a
//! value it does not like; a thread that changes the value calls
//! [`wake_one`] or [`wake_all`]. The system keeps the queue of waiters,
//! keyed on the address of the atomic: the atomic itself is ordinary memory
//! and takes no initialisation.
//!
//! | System | Calls |
//! |---|---|
//! | Linux | `futex` (`FUTEX_WAIT`, `FUTEX_WAKE`, private to the process) |
//! | macOS | `os_sync_wait_on_address`, `os_sync_wait_on_address_with_timeout`, `os_sync_wake_by_address_any`, `os_sync_wake_by_address_all`; before macOS 14.4, `__ulock_wait2`, `__ulock_wake` (`UL_COMPARE_AND_WAIT`) |
//! | Windows | `WaitOnAddress`, `WakeByAddressSingle`, `WakeByAddressAll` |
//!
//! Waiters are found by address within the process: an atomic in memory
//! shared with another process does not wake that process's waiters.
//!
//! On macOS the documented calls (`<os/os_sync_wait_on_address.h>`) need
//! macOS 14.4: they are looked up in the running system the first time
//! (`dlsym`), and used if all four are there. An older system is given the
//! calls they are made of, which the system's own libc++ and Rust's `std`
//! use, and which are not part of the documented SDK. Either way the
//! thread's `errno` is left as it was.
//!
//! WebAssembly is single-threaded here: see [`wait`] for what waiting means
//! when nobody can wake.
//!
//! ```
//! use core::sync::atomic::{AtomicU32, Ordering};
//! use oscall::sync;
//!
//! /// Blocks until `flag` is set.
//! fn wait_for(flag: &AtomicU32) -> oscall::Result<()> {
//!     // The loop is not optional: `wait` can return with nothing changed.
//!     while flag.load(Ordering::Acquire) == 0 {
//!         sync::wait(flag, 0, None)?;
//!     }
//!     Ok(())
//! }
//!
//! fn set(flag: &AtomicU32) {
//!     flag.store(1, Ordering::Release);
//!     sync::wake_all(flag);
//! }
//!
//! let flag = AtomicU32::new(0);
//! set(&flag);
//! wait_for(&flag).unwrap();
//! ```

use core::sync::atomic::AtomicU32;
use core::time::Duration;

use crate::Result;
use crate::sys;

/// Why [`wait`] returned.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[must_use = "a wait can end without the value having changed: check it again"]
pub enum WaitOutcome {
    /// The wait ended before the timeout, for one of these reasons, which
    /// the systems do not tell apart reliably:
    ///
    /// - the value was not the expected one, and the thread did not sleep;
    /// - [`wake_one`] or [`wake_all`] was called on the atomic;
    /// - nothing at all (a *spurious* wake-up), or a signal handler ran in
    ///   the thread.
    ///
    /// The caller must therefore look at the value again, and wait again if
    /// it still has to.
    Woken,
    /// The timeout passed while the thread slept. A wake-up may have raced
    /// with it: the value is worth one more look here too.
    TimedOut,
}

/// Puts the calling thread to sleep if `atomic` holds `expected`, until it
/// is woken or `timeout` passes.
///
/// The comparison and the going to sleep are one atomic step as far as
/// [`wake_one`] and [`wake_all`] are concerned: a thread that stores a new
/// value and then wakes cannot slip between the two and leave the waiter
/// asleep. If the value is not `expected`, the call returns
/// [`Woken`](WaitOutcome::Woken) at once.
///
/// `timeout` is relative, and measured on the clock
/// [`Clock::Monotonic`](crate::time::Clock::Monotonic) reads; `None` waits
/// for as long as it takes. A zero timeout never sleeps: it only compares.
/// [`TimedOut`](WaitOutcome::TimedOut) is never returned before the timeout
/// has passed on that clock. Where the system would do so, the wait ends as
/// a spurious wake-up instead: on Windows, which counts in milliseconds
/// (rounded up here) and in timer ticks, and can give up a tick early; and
/// for a timeout longer than the system can count, which is shortened (49
/// days on Windows) or taken as no timeout at all (centuries elsewhere).
///
/// See [`WaitOutcome`] for what the result does and does not tell. Spurious
/// wake-ups are rare but real on every system; an interruption by a signal
/// is reported as one, not as an error.
///
/// # WebAssembly
///
/// oscall takes WebAssembly to be single-threaded, so nobody can wake a
/// waiter. If the value is not `expected` the call returns
/// [`Woken`](WaitOutcome::Woken), as everywhere. Otherwise, with a timeout,
/// the thread sleeps for its whole length and
/// [`TimedOut`](WaitOutcome::TimedOut) is returned (on WASI; without WASI
/// there is no way to sleep and the call fails with
/// [`Unsupported`](crate::ErrorKind::Unsupported), unless the timeout is
/// zero); with no timeout the wait could never end, and the call fails with
/// [`Deadlock`](crate::ErrorKind::Deadlock) instead of hanging.
pub fn wait(atomic: &AtomicU32, expected: u32, timeout: Option<Duration>) -> Result<WaitOutcome> {
    Ok(if sys::sync::wait(atomic, expected, timeout)? {
        WaitOutcome::Woken
    } else {
        WaitOutcome::TimedOut
    })
}

/// Wakes one of the threads waiting on `atomic` in [`wait`], if there is
/// any. Which one is up to the system.
///
/// A thread that is about to wait, but has not compared the value yet, is
/// not a waiter: change the value before waking, so that it does not sleep.
///
/// Does nothing on WebAssembly, where there are no other threads.
pub fn wake_one(atomic: &AtomicU32) {
    sys::sync::wake(atomic, false);
}

/// Wakes all the threads waiting on `atomic` in [`wait`].
///
/// Does nothing on WebAssembly, where there are no other threads.
pub fn wake_all(atomic: &AtomicU32) {
    sys::sync::wake(atomic, true);
}