feat(compiler): a Job.parallel_for worker may read a state but not change one

Every pool thread runs the worker at once with the same states, so a mut state in a worker was a
race nothing reported. check_worker_ref refuses a worker whose leading states include a mut one;
threads.ludic's total moves into the words the worker is handed, under the mutex. The seeds are
regenerated (ludic-dev reseed). ludic-dev test 305 passed, selfhost-test 33 passed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Orkun ÇAKILKAYA 2026-09-27 22:04:59 +03:00
parent 7ceefa8c50
commit 7834b26ef8
6 changed files with 13354 additions and 13188 deletions

View file

@ -9,17 +9,18 @@ program Threads {
state ThreadsState {
calls: int = 0 # an atomic handle, made on the main thread before any work
lock: int = 0 # a mutex handle
total: long = 0 # guarded by `lock`
}
# out[i] = i * i: every index written exactly once, by whichever thread claimed it
function square(i: int, out: words) -> void { out[i] = i * i }
# count the call atomically, and add i to a shared total under the mutex
function tally(threads_st: mut ThreadsState, i: int, ctx: pointer) -> void {
# count the call atomically, and add i to a shared total under the mutex. A worker may read a
# state (the handles in it) but never change one - every thread runs it at once - so the total
# lives in what the worker is handed
function tally(threads_st: ThreadsState, i: int, total: words) -> void {
Sync.add(threads_st.calls, 1)
Sync.lock(threads_st.lock)
threads_st.total = threads_st.total + i
total[0] = total[0] + i
Sync.unlock(threads_st.lock)
}
@ -43,10 +44,11 @@ program Threads {
threads_st.calls = Sync.atomic()
threads_st.lock = Sync.mutex()
Job.parallel_for(N, fn tally, null)
let total = words(1)
Job.parallel_for(N, fn tally, total)
if Sync.get(threads_st.calls) == N { print(4) }
let want: long = N * (N - 1) / 2
if threads_st.total == want { print(5) }
let want = N * (N - 1) / 2
if total[0] == want { print(5) }
let ran = words(N)
Job.parallel_for(N, fn placed, ran)