Initial Commit

This commit is contained in:
SoraKatadzuma committed 2026-10-29 09:21:10 -05:00
commit defb8fa434
1625 files changed
+43449

No files matched your search

+112
View File
@@ -0,0 +1,112 @@
#! @file channel.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains channels, which hand values from the threads sending them to those
#! receiving them, in the order they were sent.
import system;
import std::containers;
module std::thread;
#! A queue that hands values from the threads sending them to those receiving
#! them: each value sent is received once, by one receiver, in the order one
#! sender sent them. A bound makes senders wait while it holds that many, and a
#! receiver waits while it holds none. Closing it wakes every waiter: senders get
#! back what they would send, receivers get nothing, and what it still held is
#! closed.
#! @tparam T What it hands over, which it owns until it is received.
pub struct channel<T> : owning {
var _held: mutex<passage<T>>;
var _sent: condition; # Notified where a value arrives.
var _taken: condition; # Notified where room is made.
}
# What a channel's mutex guards.
struct passage<T> {
var items: queue<T>;
var bound: u64;
var closed: bool;
}
#! Makes a channel.
#! @param capacity How many values it holds before senders wait, or zero for
#! no bound.
#! @returns The channel.
pub def channel<T>::new(capacity: u64): channel<T> {
return channel::<T> {
_held = mutex::<passage<T>>::new(passage::<T> { items = queue::<T>::new(), bound = capacity, closed = false }),
_sent = condition::new(),
_taken = condition::new()
};
}
#! Sends a value, waiting while the channel holds as many as its bound.
#! @param this The channel.
#! @param value The value, which a receiver owns once it receives it.
#! @returns Nothing, or the value back where the channel is closed.
pub def channel<T>::send(&mut this, value: T): result<void, T> {
var held := this._held.lock();
while !held.value().closed && held.value().bound != 0 && held.value().items.length >= held.value().bound {
this._taken.wait(&mut held);
}
if held.value().closed {
return result::<void, T> { error = move(value) };
}
held.value().items.push(move(value));
this._sent.notify_one();
return result::<void, T> { value = void {} };
}
#! Receives the value sent first of those the channel holds, waiting while it
#! holds none.
#! @param this The channel.
#! @returns The value, or nothing once the channel is closed.
pub def channel<T>::receive(&mut this): maybe<T> {
var held := this._held.lock();
while held.value().items.length == 0 && !held.value().closed {
this._sent.wait(&mut held);
}
return this.take(&mut held);
}
#! Receives the value sent first of those the channel holds, without waiting.
#! @param this The channel.
#! @returns The value, or nothing where it holds none.
pub def channel<T>::try_receive(&mut this): maybe<T> {
var held := this._held.lock();
return this.take(&mut held);
}
#! How many values a channel holds.
#! @param this The channel.
#! @returns How many.
pub def channel<T>::length(&mut this): u64 {
var held := this._held.lock();
return held.value().items.length;
}
#! Closes a channel: every thread waiting on it wakes, senders get back what
#! they send from then on, receivers get nothing, and what it held is closed.
#! @param this The channel.
pub def channel<T>::close(&mut this): void {
var held := this._held.lock();
held.value().closed = true;
held.value().items.close();
this._sent.notify_all();
this._taken.notify_all();
}
# Takes the value at the front of the channel, where it holds one.
def channel<T>::take(&mut this, held: &mut guard<passage<T>>): maybe<T> {
val there := &mut held.value();
if there.items.length == 0 {
return nothing {};
}
var front: T = move(there.items.peek());
there.items.pop();
this._taken.notify_one();
return move(&mut front);
}
+218
View File
@@ -0,0 +1,218 @@
#! @file locks.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains what guards what threads share: a mutex owning a value only one
#! thread reaches at a time, the guard lending it, a condition threads wait on
#! until another says something changed, and something run once however many
#! threads ask. Each is a word threads change atomically and wait on with
#! `system::futex_wait`, so none makes a system call but where a thread waits, or
#! one waits to be woken.
import system;
import std::time;
module std::thread;
#! A value only one thread reaches at a time: `lock` waits until no other thread
#! holds it, and gives a guard lending it, which lets go of it where it closes.
#!
#! Its word is 0 where no thread holds it, 1 where one does, and 2 where one does
#! and others may be waiting, as Drepper's "Futexes Are Tricky" has it, so
#! letting go makes a system call only where another thread may wait.
#! @tparam T What it guards, which it owns, and closes where it closes.
pub struct mutex<T> : owning {
var _word: atomic<u32>;
var _value: T;
}
#! Makes a mutex owning a value.
#! @param value What it guards.
#! @returns The mutex, which no thread holds.
pub def mutex<T>::new(value: T): mutex<T> {
return mutex::<T> { _word = atomic::<u32>::new(0), _value = move(value) };
}
#! Waits until no other thread holds a mutex, and holds it.
#! @param this The mutex.
#! @returns The guard lending what it guards, which lets go of it where it
#! closes.
pub def mutex<T>::lock(&mut this): guard<T> {
this.hold();
return guard::<T> { _mutex = this as *mut mutex<T> };
}
#! Holds a mutex where no other thread does, without waiting.
#! @param this The mutex.
#! @returns The guard where it held it, and nothing where another thread does.
pub def mutex<T>::try_lock(&mut this): maybe<guard<T>> {
if this._word.compare_exchange(0, 1, order::acquire, order::relaxed) is value {
return guard::<T> { _mutex = this as *mut mutex<T> };
}
return nothing {};
}
#! Closes what a mutex guards. No thread holds it, nor will.
#! @param this The mutex.
pub def mutex<T>::close(&mut this): void {
close(&mut this._value);
}
# Waits until no other thread holds the mutex, and holds it. Where it was held, the
# word is made 2 before waiting, so whoever lets go wakes a waiter.
def mutex<T>::hold(&mut this): void {
if this._word.compare_exchange(0, 1, order::acquire, order::relaxed) is value {
return;
}
while this._word.exchange(2, order::acquire) != 0 {
_ = system::futex_wait(this.word(), 2, -1);
}
}
# Lets go of the mutex, waking a thread waiting for it where one may be.
def mutex<T>::let_go(&mut this): void {
if this._word.exchange(0, order::release) == 2 {
_ = system::futex_wake(this.word(), 1);
}
}
# The word the mutex's threads wait on.
def mutex<T>::word(&mut this): *mut u32 {
return ((&mut this._word) as *mut atomic<u32>) as *mut u32;
}
#! Lends the value a mutex guards, to the one thread holding it, and lets go of
#! the mutex where it closes. A guard dropped as soon as it is made would let go
#! at once, so one must be kept.
#! @tparam T What the mutex guards.
@nodiscard
pub struct guard<T> : owning {
var _mutex: *mut mutex<T>;
}
#! What the mutex guards, which no other thread reaches while the guard is held.
#! @param this The guard.
#! @returns The value.
pub def guard<T>::value(&mut this): &mut T {
return &mut this._mutex[0]._value;
}
#! Lets go of the mutex.
#! @param this The guard, which holds nothing after.
pub def guard<T>::close(&mut this): void {
if this._mutex != null {
this._mutex[0].let_go();
this._mutex = null;
}
}
#! A place threads wait until another says something changed, which they look
#! at holding a mutex: a thread holding it finds what it waits for missing, and
#! waits, letting go of the mutex as it does, and holding it again once woken.
#! A thread may wake without being notified, so it looks again.
#!
#! Its word counts notifications. A thread reads it before it lets go of the
#! mutex, and waits only while it holds that, so a notification between the two
#! is never lost.
pub struct condition {
var _count: atomic<u32>;
}
#! Makes a condition.
#! @returns The condition.
pub def condition::new(): condition {
return condition { _count = atomic::<u32>::new(0) };
}
#! Lets go of a mutex and waits until notified, holding it again after.
#! @param this The condition.
#! @param held The guard of the mutex, which holds it again after.
pub def condition::wait<T>(&mut this, held: &mut guard<T>): void {
val seen := this._count.load(order::relaxed);
held._mutex[0].let_go();
_ = system::futex_wait(this.word(), seen, -1);
held._mutex[0].hold();
}
#! Lets go of a mutex and waits until notified, or until a length of time has
#! passed, holding it again after.
#! @param this The condition.
#! @param held The guard of the mutex, which holds it again after.
#! @param most How long to wait at most.
#! @returns Whether it was woken before the time ran out.
pub def condition::wait_for<T>(&mut this, held: &mut guard<T>, most: time::duration): bool {
val seen := this._count.load(order::relaxed);
held._mutex[0].let_go();
val result := system::futex_wait(this.word(), seen, most.in_nanoseconds);
held._mutex[0].hold();
return result != -110;
}
#! Wakes one thread waiting on a condition.
#! @param this The condition.
pub def condition::notify_one(&mut this): void {
_ = this._count.fetch_add(1, order::release);
_ = system::futex_wake(this.word(), 1);
}
#! Wakes every thread waiting on a condition.
#! @param this The condition.
pub def condition::notify_all(&mut this): void {
_ = this._count.fetch_add(1, order::release);
_ = system::futex_wake(this.word(), 0x7FFFFFFF);
}
# The word the condition's threads wait on.
def condition::word(&mut this): *mut u32 {
return ((&mut this._count) as *mut atomic<u32>) as *mut u32;
}
#! Runs a function once, however many threads ask: the first runs it, and the
#! rest wait until it has run.
#!
#! Its word is 0 before it runs, 1 while it runs, 2 while it runs and others
#! wait, and 3 once it has run.
pub struct once {
var _state: atomic<u32>;
}
#! Makes a `once` that has run nothing.
#! @returns It.
pub def once::new(): once {
return once { _state = atomic::<u32>::new(0) };
}
#! Runs a function where none has run, or waits until the one running has.
#! @param this The `once`.
#! @param body The function.
pub def once::run(&mut this, body: def(): void): void {
return if this._state.load(order::acquire) == 3;
if this._state.compare_exchange(0, 1, order::acquire, order::acquire) is value {
body();
if this._state.exchange(3, order::release) == 2 {
_ = system::futex_wake(this.word(), 0x7FFFFFFF);
}
return;
}
while true {
val state := this._state.load(order::acquire);
return if state == 3;
if state == 1 && this._state.compare_exchange(1, 2, order::relaxed, order::relaxed) is error {
continue;
}
_ = system::futex_wait(this.word(), 2, -1);
}
}
#! Whether a `once` has run its function.
#! @param this The `once`.
#! @returns Whether it has.
pub def once::done(&mut this): bool {
return this._state.load(order::acquire) == 3;
}
# The word the threads waiting for it wait on.
def once::word(&mut this): *mut u32 {
return ((&mut this._state) as *mut atomic<u32>) as *mut u32;
}
+189
View File
@@ -0,0 +1,189 @@
#! @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();
}