Files
std/tests/thread/threads.sakura
T
2026-12-06 13:39:23 -06:00

339 lines
11 KiB
Plaintext

# Tests of threads: what they give back, values given to them, mutexes under
# contention, conditions, channels, `once`, and threads allocating and releasing
# memory at once.
import std::math;
import std::process;
import system;
import std::testing;
import std::thread;
import std::time;
# How many owning values of the tests have been closed, from any thread.
var closed_parcels: atomic<u64>;
struct parcel : owning {
var weight: u64;
}
def parcel::close(&mut this): void {
if this.weight != 0 {
_ = closed_parcels.fetch_add(1);
this.weight = 0;
}
}
@test def threads_give_back_what_their_functions_gave(t: &mut tester): void {
# A closure refers to the locals it uses, so each thread takes its part from a
# count they share.
var sums := 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..1000u { sum += i * part; }
return sum;
}) else (e) { t.expects(false); return; };
sums.append(move(started));
}
var total: u64 = 0;
for i in 0..sums.length {
t.expects(!sums[i].finished() || sums[i].number() != 0);
total += sums[i].join();
}
t.expects(total == 499500 * 10);
# A value given to a thread is its own, and closed where its function ends.
val before := closed_parcels.load();
var given := parcel { weight = 7 };
var weighed := atomic::<u64>::new(0);
var carried := thread::spawn_with(def(p: parcel) { weighed.store(p.weight); }, move(&mut given)) else (e) {
t.expects(false);
return;
};
carried.close();
t.expects(weighed.load() == 7 && closed_parcels.load() == before + 1);
# Closing a handle waits for its thread.
var done := atomic::<bool>::new(false);
{
var slow := thread::spawn(def() {
thread::sleep(time::milliseconds(30));
done.store(true);
}) else (e) { t.expects(false); return; };
}
t.expects(done.load());
}
@test def a_mutex_keeps_an_exact_count_under_contention(t: &mut tester): void {
var count := thread::mutex::<u64>::new(0);
{
var workers := vector::<thread::handle<void>>::new();
for _ in 0..8u {
var started := thread::spawn(def() {
for _ in 0..20000u {
var held := count.lock();
held.value() += 1;
}
}) else (e) { t.expects(false); return; };
workers.append(move(started));
}
}
var held := count.lock();
t.expects(held.value() == 160000);
t.expects(count.try_lock() is none);
}
@test def a_condition_hands_work_from_producer_to_consumer(t: &mut tester): void {
var queued := thread::mutex::<vector<u64>>::new(vector::<u64>::new());
var arrived := thread::condition::new();
var consumer := thread::spawn(def(): u64 {
var sum: u64 = 0;
var taken: u64 = 0;
var held := queued.lock();
while taken < 100 {
while held.value().length == 0 {
arrived.wait(&mut held);
}
val next: u64 = held.value()[held.value().length - 1];
held.value().remove_at(held.value().length - 1);
sum += next;
taken++;
}
return sum;
}) else (e) { t.expects(false); return; };
for i in 0..100u {
var held := queued.lock();
held.value().append(i);
arrived.notify_one();
}
t.expects(consumer.join() == 4950);
# A wait for a length of time ends once it has passed.
var never := thread::condition::new();
var held := queued.lock();
val began := instant::now();
t.expects(!never.wait_for(&mut held, time::milliseconds(20)));
t.expects(began.elapsed() >= time::milliseconds(15));
}
@test def channels_keep_order_hold_to_their_bound_and_close(t: &mut tester): void {
# One sender's values arrive in the order it sent them.
var numbers := thread::channel::<u64>::new(0);
var sender := thread::spawn(def() {
for i in 0..1000u { _ = numbers.send(i); }
}) else (e) { t.expects(false); return; };
var ordered := true;
for i in 0..1000u {
match numbers.receive() {
some(got) => ordered = ordered && got == i;
none => ordered = false;
}
}
sender.close();
t.expects(ordered);
# A bound makes a sender wait while the channel holds as many.
var bounded := thread::channel::<u64>::new(2);
var most := atomic::<u64>::new(0);
var filler := thread::spawn(def() {
for i in 0..6u {
_ = bounded.send(i);
_ = most.fetch_max(bounded.length());
}
}) else (e) { t.expects(false); return; };
thread::sleep(time::milliseconds(20));
t.expects(bounded.length() == 2);
var received: u64 = 0;
for _ in 0..6u {
if bounded.receive() is some(_) { received++; }
}
filler.close();
t.expects(received == 6 && most.load() <= 2);
# Closing ends a receiver waiting, gives back what is sent after, and closes
# what the channel held.
var parcels := thread::channel::<parcel>::new(0);
var waiting := thread::channel::<u64>::new(0);
var receiver := thread::spawn(def(): bool { return waiting.receive() is none; }) else (e) {
t.expects(false);
return;
};
thread::sleep(time::milliseconds(10));
waiting.close();
t.expects(receiver.join());
val before := closed_parcels.load();
_ = parcels.send(parcel { weight = 1 });
_ = parcels.send(parcel { weight = 2 });
parcels.close();
t.expects(closed_parcels.load() == before + 2);
match parcels.send(parcel { weight = 3 }) {
value(_) => t.expects(false);
error(back) => t.expects(back.weight == 3);
}
t.expects(parcels.receive() is none);
}
@test def once_runs_one_function_however_many_ask(t: &mut tester): void {
var first := thread::once::new();
var runs := atomic::<u64>::new(0);
var finished := atomic::<u64>::new(0);
{
var askers := vector::<thread::handle<void>>::new();
for _ in 0..16u {
var started := thread::spawn(def() {
first.run(def() {
thread::sleep(time::milliseconds(5));
_ = runs.fetch_add(1);
});
# Every thread sees it run once it returns.
if runs.load() == 1 { _ = finished.fetch_add(1); }
}) else (e) { t.expects(false); return; };
askers.append(move(started));
}
}
t.expects(runs.load() == 1 && finished.load() == 16 && first.done());
}
# A list of numbers, each node owning the next.
struct chained {
var value: u64;
var next: maybe<box<chained>>;
}
@test def threads_allocate_and_release_at_once(t: &mut tester): void {
var workers := vector::<thread::handle<u64>>::new();
var next_worker := atomic::<u64>::new(0);
for _ in 0..4u {
var started := thread::spawn(def(): u64 {
val w := next_worker.fetch_add(1);
var sum: u64 = 0;
for _ in 0..20u {
# A list of boxes, each allocated here and released as the list closes.
var front: maybe<box<chained>> = nothing {};
for i in 0..300u {
front = box::<chained>::new(chained { value = i * w, next = move(&mut front) });
}
var at: maybe<&chained> = nothing {};
if front is some(&first) { at = first.get(); }
while at is some(&each) {
sum += each.value;
at = nothing {};
if each.next is some(&next) { at = next.get(); }
}
}
return sum;
}) else (e) { t.expects(false); return; };
workers.append(move(started));
}
var all: u64 = 0;
for i in 0..workers.length {
all += workers[i].join();
}
# Each adds its own number times 44850, the sum below 300, twenty times.
t.expects(all == 44850 * 20 * 6);
}
@test def blocks_released_by_another_thread_keep_what_they_hold(t: &mut tester): void {
# Blocks of many sizes are made in two threads and released in two others,
# more of each size than a thread keeps to hand out again, and each holds what
# was written in it until it is released, so none is handed out twice.
var line := channel::<u64>::new(64);
var spoiled := atomic::<u64>::new(0);
var released := atomic::<u64>::new(0);
var consumers := vector::<thread::handle<void>>::new();
for _ in 0..2u {
var started := thread::spawn(def() {
while line.receive() is some(address) {
return if address == 0;
val words := address as *mut u64;
for k in 1..words[0] {
if words[k] != address + k {
_ = spoiled.fetch_add(1);
}
}
raw_release(address as *mut u8);
_ = released.fetch_add(1);
}
}) else (e) { t.expects(false); return; };
consumers.append(move(started));
}
var producers := vector::<thread::handle<void>>::new();
for p in 0..2u {
var started := thread::spawn_with(def(seed: u64) {
var x := seed;
for _ in 0..5000u {
x = math::wrapping_add(math::wrapping_mul(x, 6364136223846793005), 1442695040888963407);
val count := 2 + (x >> 40) % 60;
val words := raw_allocate(count * 8) as *mut u64;
words[0] = count;
for k in 1..count {
words[k] = words as u64 + k;
}
_ = line.send(words as u64);
}
}, p + 1) else (e) { t.expects(false); return; };
producers.append(move(started));
}
for i in 0..producers.length {
producers[i].join();
}
_ = line.send(0);
_ = line.send(0);
for i in 0..consumers.length {
consumers[i].join();
}
t.expects(spoiled.load() == 0 && released.load() == 10000);
}
# Windows ends few of the waits of the system where another thread stops the
# program, so std waits in short ones, and a program a thread stops ends at once,
# though its first thread sleeps or waits for a child, and another pauses.
when os == windows {
# Runs a function in a copy of the program, giving whether the copy exited with
# 7, and how long it took to, in nanoseconds.
def exits_with_seven(run: def(): void, took: &mut i64): bool {
val began := clock(clock_kind::steady);
val stopped := copied(run);
took = clock(clock_kind::steady) - began;
return stopped.exited && stopped.code == 7;
}
@test def a_thread_exiting_ends_the_waits_of_the_others(t: &mut tester): void {
var quick: i64 = 0;
t.expects(exits_with_seven(def() { exit(7); }, &mut quick));
# The program gives a thread five seconds to come back from the system before
# ending it, which each copy stops well within.
var slept: i64 = 0;
t.expects(exits_with_seven(def() {
var paused := thread::spawn(def() { pause(); }) else (e) { return; };
var exiting := thread::spawn(def() {
thread::sleep(time::milliseconds(20));
exit(7);
}) else (e) { return; };
thread::sleep(time::seconds(60));
}, &mut slept));
t.expects(slept - quick < 2500000000);
# The child reads until the copy, which holds what it reads, stops.
var waited: i64 = 0;
t.expects(exits_with_seven(def() {
var reader := process::command::new("findstr");
reader.argument("x");
reader.input(process::stdio::piped);
reader.output(process::stdio::none);
var running := reader.spawn() else (_) { return; };
var exiting := thread::spawn(def() {
thread::sleep(time::milliseconds(20));
exit(7);
}) else (e) { return; };
var status: process_status;
_ = wait(running.id as i64, &mut status);
}, &mut waited));
t.expects(waited - quick < 2500000000);
}
}