Concurrency: next designs (C3 select, fd readiness, C6 multi-core)
Status: design only, no code. Measured with bench/concurrency.py (macOS arm64 laptop): spawn+join 1.7 us,
task switch 18 ns, channel round trip 65 ns, 10,000 tasks 77 ms and 626 MiB RSS (about 62 KiB per live
task). SPEC.md ("Tasks and channels") is the contract; CONCURRENCY.md is the older plan.
Order: step 0, select, fd readiness, multi-core. Each step must work on all three hosted targets and in the self-hosted build.
0. Before select: safety and tests (done)
- Guard (3306): each task stack has a
PROT_NONEregion of 64 MiB + 64 KiB below 64 KiB of stack, so one frame of at most 64 MiB (E090) cannot jump over it.conc_stack_x64.kn,conc_stack_arm.kn. channel[[]u8](3307): the peephole removed the store of the length;release_tempsprotects all words. A failed send or an undelivered item frees each owner of the message (3324). Slices of owners areE164.- End-to-end tests:
tests/test_concurrency.sh.
1. select (C3)
Surface
select {
recv(rx_a, &mut ok_a) as value { ... } // first ready case runs; value is T
send(tx_b, move item) { ... } // runs when the send completed
after(50) { ... } // timeout in ms, one per select
default { ... } // never blocks; excludes after
}
selectis a statement. Cases are scanned in source order, so the winner is deterministic.- Cancellation is not a case. A cancelled scope makes every blocked case ready with
ok=falseor a failed send, asrecvandsenddo today. The body testsok. recv ... as namebinds the received value, zero ifokis false. Asendcase withmovemoves the value only when that case wins.- New
E166: a bad case kind; twoafter;defaultwithafter; one channel twice; an empty select.
Runtime
- Today a task waits on one channel: the wait queues link the TCB through its word at +8, and the TCB words at +120, +128 and +136 hold the value pointer, flags and the channel. One task cannot sit in two queues, so select needs wait nodes.
- Add a wait node of four words: next, TCB, case index, value pointer. Plain
sendandrecvuse a node inside the TCB (same cost as now).selectbuilds one node per case in its stack frame. - New
kern_select(table, count, timeout_ms, has_default) -> index. Pass 1 scans in order and completes the first ready case without blocking. If none is ready and there is nodefault, it queues one node per channel and, ifafteris present, a sleep-list entry. Then it callskern_sched_switch_next. - The waker (
kern_chan_send,kern_chan_recv,kern_chan_close,kern_chan_wake_cancelled) pops a node, sets the case index in the TCB, moves the value, and callskern_chan_unwaitfor the other nodes. The winner is the first waker. A timer or cancel wake removes all nodes the same way. No lost wake-up is possible because all queue changes run on the one scheduler thread.
Files
| File | Change |
|---|---|
compiler/src/lexer/token.kn | new words select, after, default (none is a keyword today) |
compiler/src/parser/parse.kn, compiler/src/builtins/names.kn | SELECT_STMT node (next id after 48), case list |
compiler/src/typing/concurrency.kn | select_statement: case types, as binding, E166 |
compiler/src/ownership/concurrency.kn | each case is a branch; move in a send case moves only in that branch |
compiler/src/backend/concurrency.kn | build the case table in the frame, call kern_select, dispatch on index |
compiler/src/runtime_extra/conc_chan_x64.kn, conc_chan_arm.kn, conc_x64.kn, conc_arm.kn | wait nodes, kern_select, wakers, timer entry for after |
compiler/src/format/, api/expressions.kn, testhash/, rules/ | format, API, test hash, rules for the new node |
SPEC.md, tests/test_select.sh, tests/errors/ | contract (python3 .cip/gen-spec.py); order, timeout, close, cancel, E166 |
2. Socket readiness in tasks
Goal: std.http runs one task per connection. A task that waits for an fd must not block the others.
Design
- New builtin
fd_wait(fd: i64, events: u64) -> boolin the concurrency block (afterYIELD). It returns true when the fd is ready, false on cancel or error.eventsis read or write. - The scheduler owns one poller, created on first use with the existing
poller_newruntime code (compiler/src/runtime_os/net.kn: epoll on Linux, kqueue on macOS). It is never visible to the user. fd_waitregisters the fd one-shot (EPOLLONESHOT;EV_ADD|EV_ONESHOTon kqueue), stores the TCB pointer as event data, links the task on a wait list in the TCB, and switches away.- The idle path of
kern_sched_switch_nextchanges. Today it sleeps withkern_sleep_msuntil the next timer. New rule: if any task waits on an fd, callkern_poller_waitwith timeout = time to the next sleeper (or infinite if none). Else keep the OS sleep. - While tasks are ready, poll with timeout 0 once per 64 switches or 1 ms, so busy programs see sockets.
- Wake: for each event (also
EPOLLHUP,EV_EOF), find the TCB, move it to the ready queue. Cancel removes the registration withEPOLL_CTL_DEL/EV_DELETEand wakes the task with false. - Sockets stay non-blocking (
fd_set_nonblocking). The task loop is: read; if -2 callfd_wait; retry.std.netgets thin helperswait_readableandwait_writable;std/http/server.kncan then drop its own poller loop and spawn one task per accepted connection. - Not in this step: blocking files and DNS stay blocking (see 3, option B).
Files
| File | Change |
|---|---|
compiler/src/builtins/names.kn | FD_WAIT id, name, count, range check of concurrency() |
compiler/src/typing/concurrency.kn, backend/concurrency.kn | type of fd_wait (inside a scope); call kern_sched_fd_wait |
compiler/src/runtime_extra/conc_x64.kn, conc_arm.kn | wait list, idle path, poll-while-busy, cancel |
compiler/src/runtime_os/net.kn | share the kevent / epoll wrappers with the scheduler; one-shot flags |
std/net/poll.kn, std/http/server.kn | helpers and task-per-connection server |
SPEC.md, tests/test_fdwait.sh | contract; socketpair test: a waiting task and a CPU task both finish; cancel |
Risk: one-shot re-arm costs a syscall per wait (measure with bench/http/load.sh); test an fd closed while registered.
3. Multi-core (C6)
Helps: tasks already share nothing, so no Send/Sync rules are needed. Spawn arguments are scalars, moved owners and channel endpoints; views
cannot cross. Memory is shared only through channels and the scope tree. kern_alloc is one mmap per
allocation, so the allocator needs no lock.
Blocks: all scheduler state is global (kern_sched_*): ready queue, sleep list, current task, scope depth, loop
budget, stack and TCB pools. Channels and scope joins assume one thread. The language has no atomics or
memory-order rules. Linux uses raw syscalls, so threads need clone and futex assembly; macOS can call
pthread_create from libSystem.
Options
| Option | Idea | Cost | Verdict |
|---|---|---|---|
| A. Full M:N work stealing | N threads, steal ready tasks, Shared/Atomic | atomics, memory model, per-thread state, stolen running tasks | too large now |
| B. Blocking offload only | one scheduler thread; a pool runs blocking calls (files, DNS, process wait) | small; no change to task semantics | useful, not parallel compute |
| C. Pinned workers | N scheduler threads, each with its own queues; a task stays on its thread; spawn places it by round-robin or a scope setting | per-thread state, locked channels, atomic cancel flag and join word | recommended first |
| D. C plus stealing of unstarted tasks | an idle worker takes a task that has not run yet | one extra lock per queue | later, on top of C |
Recommendation: do C, default one thread, so every current program and test keeps its exact deterministic behaviour.
scope threads=N { ... } (or a KERN_THREADS override for tests) enables N workers for that scope tree.
- Per-thread scheduler block. Put the
kern_sched_*globals in a struct reached through one reserved register or thread-local slot (arm64tpidr_el0, x64fs). The code inconc_*.knchanges from absolute symbols to base-plus-offset. - Channels. Add a lock word (spin, then futex or
__ulock_wait) to the 96-byte channel object. A wake of a task on another thread puts the TCB on that thread's inbox and signals its idle futex. - Scope. The cancel flag and the child-list join word become atomic.
kern_task_joinwaits with the same inbox signal. - Atomics in the runtime only:
ldaxr/stlxr(or LSEcasal) on arm64,lock cmpxchgon x64. The language gets no atomic builtin in this step, so no memory-order rules reach user code. - Promise: with
threads=N, a program that communicates only through channels gives the same results; only the interleaving of independent tasks changes. Theselectscan stays in source order.
Files
| File | Change |
|---|---|
compiler/src/runtime_extra/conc_x64.kn, conc_arm.kn, conc_chan_x64.kn, conc_chan_arm.kn | per-thread block, locks, inbox, atomic cancel/join |
compiler/src/runtime_x64, runtime_arm, runtime_mac | thread start (clone+futex, pthread_create), idle park and wake |
compiler/src/parser/parse.kn, typing/concurrency.kn, backend/concurrency.kn | scope threads=N |
tests/test_parallel.sh, bench/concurrency.py | speed-up on CPU tasks; 100k messages on 4 workers; cancel across threads |
Exit test: CPU tasks run 3x faster on 4 threads; threads=1 output is byte-identical; 1M messages never hang. |
4. Facts not in SPEC.md, and open decisions
- Stack overflow in
mainis not trapped: it raises a signal (exit 138 on macOS). For a task stack see 0. - A blocked program sleeps 1 ms per idle round, forever.
- Open: spelling
scope threads=Nor an environment setting; is 64 KiB per task (626 MiB for 10,000) enough.