Files
std/thread/thread.sakura
T

189 lines
6.9 KiB
Plaintext
Raw Normal View History

2026-10-26 09:42:00 -05:00
#! @file thread.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains threads: functions running at the same time as the program, sharing
#! its memory, each waited for where its handle closes, and giving back what it
#! gave to whoever joins it.
#!
#! Threads share all the program's memory, so what two of them use at once is
#! guarded, by a `mutex`, an `atomic`, or a `channel` handing values over. Two
#! threads touching the same memory that is not, at least one writing, with
#! neither happening before the other, is a race, which is the program's
#! mistake: what either then reads is not defined. A closure a thread runs
#! refers to the locals it uses, as every closure does, so the scope they are
#! in waits for the thread before it ends; what is given to `spawn_with` is the
#! thread's alone.
#!
#! A thread is waited for where its handle closes, so one started in a scope ends
#! before the scope does, and what it uses from that scope outlives it. A fault
#! in any thread stops the program, with that thread's trace, and `system::exit`
#! from any thread stops them all. Signal handlers run in the thread the program
#! began with. In the virtual machine, threads take turns, one running bytecode
#! at a time, and let one another run as they wait and every so often between;
#! in an executable they run in parallel. A program right in one is right in the
#! other. No thread starts while compiling.
import system;
import std::time;
module std::thread;
#! A thread running a function, which is waited for where the handle closes,
#! and which gives back what the function gave.
#! @tparam T What the function gives, `void` where it gives nothing.
pub struct handle<T> : owning {
var _job: *mut outcome<T>;
var _number: i64;
}
# What a thread and its handle share, on the heap: whether the thread is done,
# what its function gave, and how many of the two still hold it, so whichever
# lets go last gives it back.
struct outcome<T> {
var finished: atomic<u32>; # 1 once the value is there.
var holders: atomic<u32>; # The handle and the thread, while each holds it.
var value: T;
}
# What a thread is given: its outcome, then the function it runs, which it owns.
struct job<T, F> {
var outcome: outcome<T>;
var body: F;
}
# A function given a value it then owns, run as one given nothing.
struct carrying<A> : invokable<def(): void> {
var body: def(A): void;
var given: A;
}
def carrying<A>::invoke(&mut this): void {
this.body(move(&mut this.given));
}
#! Starts a thread running a function, whose value joining the thread gives
#! back, as `void` where it gives nothing.
#! @tparam T What the function gives.
#! @param body The function, which may use the locals of the scope starting
#! the thread while the handle is open, as the handle closing
#! waits for the thread.
#! @returns The thread's handle, or why it did not start, which keeps what
#! `body` refers to.
pub def spawn<T>(@kept body: def(): T): result<handle<T>, io_error> {
return start_job::<T, def(): T>(body);
}
#! Starts a thread running a function given a value, which the thread then owns
#! alone, and closes where the function ends.
#! @param body The function.
#! @param given What it is given.
#! @returns The thread's handle, or why it did not start, which keeps what
#! `body` refers to.
pub def spawn_with<A>(@kept body: def(A): void, given: A): result<handle<void>, io_error> {
return start_job::<void, carrying<A>>(carrying::<A> { body = body, given = move(&mut given) });
}
# Starts a thread running what a job holds, which the job then owns.
def start_job<T, F>(body: F): result<handle<T>, io_error> where F: invokable<def(): T> {
val made := raw_allocate_zeroed(size_of::<job<T, F>>()) as *mut job<T, F>;
made[0].outcome.holders.store(2, order::relaxed);
made[0].body = move(&mut body);
val number := system::start(run_job::<T, F>, made as *mut u8);
if number < 0 {
close(&mut made[0].body);
raw_release(made as *mut u8);
return system::error_of(number);
}
return handle::<T> { _job = made as *mut outcome<T>, _number = number };
}
# What a thread runs: its job's function, whose value it leaves for the handle,
# then the function closed, as the thread owns it.
def run_job<T, F>(context: *mut u8): void where F: invokable<def(): T> {
val made := context as *mut job<T, F>;
val body := &mut made[0].body;
made[0].outcome.value = body();
made[0].outcome.finished.store(1, order::release);
_ = system::futex_wake(((&mut made[0].outcome.finished) as *mut atomic<u32>) as *mut u32, 0x7FFFFFFF);
close(&mut made[0].body);
let_go::<T>(made as *mut outcome<T>);
}
# Lets go of what a thread and its handle share, giving it back where the other
# let go of it already.
def let_go<T>(at: *mut outcome<T>): void {
if at[0].holders.fetch_sub(1, order::acq_rel) == 1 {
raw_release(at as *mut u8);
}
}
#! Waits for a thread to end, then gives what its function gave.
#! @param this The handle, which holds nothing after; joining it again stops
#! the program.
#! @returns What the function gave.
pub def handle<T>::join(&mut this): T {
if this._number == 0 {
fault("The thread was joined already.");
}
this.wait();
this._number = 0;
# The thread left what it gave before it said it finished.
return move(&mut this._job[0].value);
}
#! Whether a thread has ended, so joining it would not wait.
#! @param this The handle.
#! @returns Whether it has.
pub def handle<T>::finished(&this): bool {
return this._number == 0 || this._job[0].finished.load(order::acquire) == 1;
}
#! The number the thread is known by, which `id` gives within it.
#! @param this The handle.
#! @returns The number, or 0 once it was joined.
pub def handle<T>::number(&this): u64 {
return this._number as u64;
}
#! Waits for a thread where it was not joined, then closes what its function
#! gave.
#! @param this The handle, which holds nothing after.
pub def handle<T>::close(&mut this): void {
return if this._job == null;
if this._number != 0 {
this.wait();
close(&mut this._job[0].value);
this._number = 0;
}
let_go::<T>(this._job);
this._job = null;
}
# Waits until the thread has left what its function gave.
def handle<T>::wait(&mut this): void {
val word := ((&mut this._job[0].finished) as *mut atomic<u32>) as *mut u32;
while this._job[0].finished.load(order::acquire) == 0 {
_ = system::futex_wait(word, 0, -1);
}
}
#! Waits for a length of time, letting other threads run.
#! @param length How long.
pub def sleep(length: time::duration): void {
time::sleep(length);
}
#! The number the system knows the calling thread by.
#! @returns The number.
pub def id(): u64 {
return system::thread_id();
}
#! How many processors the program may run on, which is how many of its threads
#! run at once in an executable.
#! @returns How many, at least one.
pub def cpu_count(): u32 {
return system::cpu_count();
}