libc/thread.kur
//! Raw POSIX threads, under `std::thread`.
// thread.c, linked with `-lpthread`.
//
// A thin wrapper over pthread_create/join. `Thread!` is linear, so every
// spawned thread is joined exactly once, and a failure is the errno. `spawn`
// is `unsafe`: `arg`'s pointee becomes reachable from two independently
// scheduled call stacks with no ordering between them, and nothing here
// tracks which stack may touch it when. `std::thread::spawn` is the safe,
// closure-based layer built on this one.
use core::mem::alloca;
use core::option::Result;
/// The errno of the failed `kur_libc_thread_create`, read at once.
extern "C" fn kur_libc_thread_error() -> i32;
/// A new thread running `entry(arg)`, as an opaque handle; or NULL.
extern "C" fn kur_libc_thread_create(entry: unsafe fn(*u8) -> *u8, arg: *u8) -> *u8;
/// Joins the thread and frees the handle, even when the join fails: 0 with
/// what `entry` returned in `*out_result`, or the errno.
extern "C" fn kur_libc_thread_join(handle: *u8, out_result: *(*u8)) -> i32;
/// A running thread, to be joined once. No raw handle extraction or safe
/// construction outside this module.
struct Thread! {
handle: *u8,
}
/// Spawns an OS thread running `entry(arg)`; `join` returns what `entry`
/// returns. Caller: `entry(arg)` is a call whose obligations hold on the new
/// thread, `arg`'s pointee stays valid for as long as the new thread may use
/// it, and every access to it from either thread is safe to interleave. This
/// call establishes no synchronization. On failure, the errno: no thread
/// ran, so `entry` was not called.
unsafe fn spawn(entry: unsafe fn(*u8) -> *u8, arg: *u8) -> Result[Thread!, i32] {
let handle = unsafe kur_libc_thread_create(entry, arg);
if unsafe (handle as usize) == 0usize {
Result::Err.(unsafe kur_libc_thread_error())
} else {
Result::Ok.(Thread!.{ handle })
}
}
impl Thread! {
/// Blocks until the thread exits, consuming the handle (freed even when
/// the join fails): what `entry` returned, or the errno. Caller: uses the
/// `*u8` that comes back only as what `entry` made it; nothing here
/// knows what it points to.
unsafe fn join(self) -> Result[*u8, i32] {
let { handle } = self;
let out = unsafe alloca[*u8]();
let status = unsafe kur_libc_thread_join(handle, out);
if status != 0i32 {
Result::Err.(status)
} else {
Result::Ok.(unsafe *out)
}
}
}