#! @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 : owning { var _job: *mut outcome; 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 { var finished: atomic; # 1 once the value is there. var holders: atomic; # 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 { var outcome: outcome; var body: F; } # A function given a value it then owns, run as one given nothing. struct carrying : invokable { var body: def(A): void; var given: A; } def carrying::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(@kept body: def(): T): result, io_error> { return start_job::(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(@kept body: def(A): void, given: A): result, io_error> { return start_job::>(carrying:: { body = body, given = move(&mut given) }); } # Starts a thread running what a job holds, which the job then owns. def start_job(body: F): result, io_error> where F: invokable { val made := raw_allocate_zeroed(size_of::>()) as *mut job; made[0].outcome.holders.store(2, order::relaxed); made[0].body = move(&mut body); val number := system::start(run_job::, 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:: { _job = made as *mut outcome, _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(context: *mut u8): void where F: invokable { val made := context as *mut job; 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) as *mut u32, 0x7FFFFFFF); close(&mut made[0].body); let_go::(made as *mut outcome); } # Lets go of what a thread and its handle share, giving it back where the other # let go of it already. def let_go(at: *mut outcome): 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::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::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::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::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::(this._job); this._job = null; } # Waits until the thread has left what its function gave. def handle::wait(&mut this): void { val word := ((&mut this._job[0].finished) as *mut atomic) 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(); }