std/thread.kur
//! Threads: `spawn` runs a closure on a new OS thread, and `Thread!::join`
//! waits for it and returns what it returned.
//!
//! The closure moves what it captured into the new thread. There is no
//! `detach`: every spawned thread's result must reach a `join`, so a linear
//! value it produces can never be stranded with nobody left to destroy it.
//!
//! `spawn` is safe to call. Holding a value does not by itself grant
//! permission to act on it, so moving an environment into another thread is
//! inert by itself: a linear environment transfers exclusive ownership, and
//! the checker rejects any further use of what was captured; one that is
//! `Copy` with no raw pointer in it is plain data, with nothing to race on;
//! and one that is or holds a raw pointer grants no access by existing,
//! since every dereference of it, in either thread, needs its own `unsafe`.
//!
//! Shared mutable state should cross as `std::cap::Exclusive!` or `Shared!`
//! rather than a bare pointer: both are linear, so moving or splitting one
//! into the closure is the same ownership transfer as any linear value. A
//! closure cannot mention a brand its block opened (`let exists 't. ...`),
//! so a capability over one is sent by a function generic over the brand,
//! where it is a parameter, which calls `spawn`:
//! `forall 't. fn work(tag: Exclusive!['t], bytes: Slice[u8, 't])`.
// Built on `libc::thread`'s raw pthread wrapper. `SpawnPayload[Env, Ret]`
// and `ResultBox[Ret]` box the closure and its result on the heap so they
// can cross that layer's raw `unsafe fn(*u8) -> *u8` boundary.
use package as std;
use alloc::heap::HeapAllocator;
use core::mem::sizeof;
use core::option::Result;
use core::process::trap;
use libc::thread::{spawn as raw_spawn, Thread! as RawThread!};
use std::io::Error;
/// The closure `spawn` hands the new thread, boxed on the heap for
/// `trampoline` to take. Used by `spawn`; not meant for direct use.
forall Env, Ret.
struct SpawnPayload {
f: closure[Env]() -> Ret,
}
/// `present` gives the box bytes even when `Ret` has none (`()`, a
/// capability), so it can be stored and loaded through a pointer.
forall Ret.
struct ResultBox {
value: Ret,
present: bool,
}
/// A thread `spawn` started, whose closure returns a `Ret`; `join` waits for
/// it.
forall Ret.
struct Thread! {
raw: RawThread!,
}
/// Runs on the new thread, instantiated once per `(Env, Ret)`. Takes
/// ownership of the heap payload `spawn` built, frees the box, calls the
/// closure exactly once, and boxes the result for `join` to unbox.
///
/// Caller: `raw` is the `SpawnPayload[Env, Ret]` box `spawn` built for
/// this same `(Env, Ret)`, owned by nothing else. It is read, freed and its
/// closure called; any other pointer is read and freed as one.
forall Env, Ret.
unsafe fn trampoline(raw: *u8) -> *u8 {
let typed_in = unsafe (raw as *SpawnPayload[Env, Ret]);
let payload = unsafe *typed_in;
let { f } = payload;
let reclaimed = unsafe HeapAllocator::adopt_raw(raw);
let freed = HeapAllocator::drop(reclaimed);
let value = f();
let out = HeapAllocator::alloc(sizeof[ResultBox[Ret]]());
let out_raw = out.into_raw();
let typed_out = unsafe (out_raw as *ResultBox[Ret]);
unsafe *typed_out = ResultBox.{ value, present: true };
unsafe (typed_out as *u8)
}
/// Spawns an OS thread running `f()`; `join` returns `f`'s result, typed
/// as `Ret`, which may be a zero-size type such as `()`. The module's
/// overview explains why this is safe to call. When no thread can be
/// started, `f` comes back unrun with the error, so what it captured is
/// still the caller's.
forall Env, Ret.
fn spawn(f: closure[Env]() -> Ret) -> Result[Thread![Ret], (closure[Env]() -> Ret, Error)] {
let payload = SpawnPayload.{ f };
let boxed = HeapAllocator::alloc(sizeof[SpawnPayload[Env, Ret]]());
let raw = boxed.into_raw();
let typed = unsafe (raw as *SpawnPayload[Env, Ret]);
unsafe *typed = payload;
// `raw_spawn`'s obligation: `raw` is the box just written, which only
// the new thread's `trampoline[Env, Ret]` reads, and only when the
// thread starts; this thread reads it again only when it does not.
let spawned = unsafe raw_spawn(trampoline[Env, Ret], raw);
match spawned {
Err(errno) => {
// No thread was started, so the box is still this call's.
let { f } = unsafe *typed;
let freed = HeapAllocator::drop(unsafe HeapAllocator::adopt_raw(raw));
Result::Err.((f, Error.{ errno }))
},
Ok(raw_thread) => Result::Ok.(Thread!.{ raw: raw_thread }),
}
}
forall Ret.
impl Thread![Ret] {
/// Blocks until the thread exits, consuming the handle, and returns
/// the `Ret` value `f` produced, so every thread's result reaches
/// exactly one `join`. Safe, unlike `libc::thread::Thread!::join`: no
/// raw pointer escapes, and the pointer read back is the
/// `ResultBox[Ret]` `trampoline` built for this same `Ret`, which
/// nothing else writes through. The box is freed after unboxing.
///
/// `pthread_join` fails only for a thread that is not joinable, is
/// the caller, or would deadlock, and a `Thread!` is none of these: a
/// thread `spawn` started, joined once, by a thread that holds its
/// handle and so is not it. A failure would leave the result
/// unreachable, so it traps rather than return without one.
fn join(self) -> Ret {
let { raw } = self;
let joined = unsafe raw.join();
match joined {
Err(errno) => trap(),
Ok(result_ptr) => {
let typed = unsafe (result_ptr as *ResultBox[Ret]);
let boxed_result = unsafe *typed;
let { value, present } = boxed_result;
let reclaimed = unsafe HeapAllocator::adopt_raw(result_ptr);
let freed = HeapAllocator::drop(reclaimed);
value
},
}
}
}