Files
sakurac/tests/programs/threads_1.sakura
T
2026-12-06 13:52:57 -06:00

98 lines
2.9 KiB
Plaintext

import std::io;
import std::thread;
# Threads giving back what they computed, a count under a mutex, a pipeline of
# channels, something run once, and a value a thread owns, each the same in the
# machine, which runs them by turns, and in an executable, which runs them at
# once.
struct parcel : owning {
var weight: u64;
}
def parcel::close(&mut this): void {
if this.weight != 0 {
io::println($"closed a parcel of {this.weight}");
this.weight = 0;
}
}
def main(): void {
# Sums of parts, each its own thread's, which it takes from a count they
# share, as a closure refers to the locals it uses.
var parts := vector::<thread::handle<u64>>::new();
var next_part := atomic::<u64>::new(1);
for _ in 1..5u {
var started := thread::spawn(def(): u64 {
val part := next_part.fetch_add(1);
var sum: u64 = 0;
for i in 0..10000u { sum += i * part; }
return sum;
}) else (e) { io::println($"no thread: {e}"); return; };
parts.append(move(started));
}
var total: u64 = 0;
for i in 0..parts.length { total += parts[i].join(); }
io::println($"parts {total}");
# A count four threads add to under a mutex.
var count := thread::mutex::<u64>::new(0);
{
var adders := vector::<thread::handle<void>>::new();
for _ in 0..4u {
var started := thread::spawn(def() {
for _ in 0..5000u {
var held := count.lock();
held.value() += 1;
}
}) else (e) { return; };
adders.append(move(started));
}
}
{
var held := count.lock();
io::println($"count {held.value()}");
}
# A pipeline: numbers, squared by one thread, summed by another.
var numbers := thread::channel::<u64>::new(4);
var squares := thread::channel::<u64>::new(4);
var squarer := thread::spawn(def() {
while numbers.receive() is some(n) { _ = squares.send(n * n); }
squares.close();
}) else (e) { return; };
var summer := thread::spawn(def(): u64 {
var sum: u64 = 0;
var seen: u64 = 0;
while seen < 100 {
if squares.receive() is some(s) { sum += s; }
seen++;
}
return sum;
}) else (e) { return; };
for n in 1..101u { _ = numbers.send(n); }
io::println($"squares {summer.join()}");
numbers.close();
squarer.close();
# Something eight threads ask for, run once.
var setup := thread::once::new();
var runs := atomic::<u64>::new(0);
{
var askers := vector::<thread::handle<void>>::new();
for _ in 0..8u {
var started := thread::spawn(def() { setup.run(def() { _ = runs.fetch_add(1); }); }) else (e) { return; };
askers.append(move(started));
}
}
io::println($"once {runs.load()}");
# A value given to a thread, which closes it where its function ends.
var given := parcel { weight = 9 };
var carried := thread::spawn_with(def(p: parcel) { io::println($"carried {p.weight}"); }, move(&mut given)) else (e) {
return;
};
carried.close();
io::println($"cpus {thread::cpu_count() >= 1}");
}