Kern
On this page

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_NONE region 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_temps protects all words. A failed send or an undelivered item frees each owner of the message (3324). Slices of owners are E164.
  • 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
}
  • select is 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=false or a failed send, as recv and send do today. The body tests ok.
  • recv ... as name binds the received value, zero if ok is false. A send case with move moves the value only when that case wins.
  • New E166: a bad case kind; two after; default with after; 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 send and recv use a node inside the TCB (same cost as now). select builds 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 no default, it queues one node per channel and, if after is present, a sleep-list entry. Then it calls kern_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 calls kern_chan_unwait for 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

FileChange
compiler/src/lexer/token.knnew words select, after, default (none is a keyword today)
compiler/src/parser/parse.kn, compiler/src/builtins/names.knSELECT_STMT node (next id after 48), case list
compiler/src/typing/concurrency.knselect_statement: case types, as binding, E166
compiler/src/ownership/concurrency.kneach case is a branch; move in a send case moves only in that branch
compiler/src/backend/concurrency.knbuild 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.knwait 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) -> bool in the concurrency block (after YIELD). It returns true when the fd is ready, false on cancel or error. events is read or write.
  • The scheduler owns one poller, created on first use with the existing poller_new runtime code (compiler/src/runtime_os/net.kn: epoll on Linux, kqueue on macOS). It is never visible to the user.
  • fd_wait registers the fd one-shot (EPOLLONESHOT; EV_ADD|EV_ONESHOT on 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_next changes. Today it sleeps with kern_sleep_ms until the next timer. New rule: if any task waits on an fd, call kern_poller_wait with 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 with EPOLL_CTL_DEL / EV_DELETE and wakes the task with false.
  • Sockets stay non-blocking (fd_set_nonblocking). The task loop is: read; if -2 call fd_wait; retry. std.net gets thin helpers wait_readable and wait_writable; std/http/server.kn can 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

FileChange
compiler/src/builtins/names.knFD_WAIT id, name, count, range check of concurrency()
compiler/src/typing/concurrency.kn, backend/concurrency.kntype of fd_wait (inside a scope); call kern_sched_fd_wait
compiler/src/runtime_extra/conc_x64.kn, conc_arm.knwait list, idle path, poll-while-busy, cancel
compiler/src/runtime_os/net.knshare the kevent / epoll wrappers with the scheduler; one-shot flags
std/net/poll.kn, std/http/server.knhelpers and task-per-connection server
SPEC.md, tests/test_fdwait.shcontract; 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

OptionIdeaCostVerdict
A. Full M:N work stealingN threads, steal ready tasks, Shared/Atomicatomics, memory model, per-thread state, stolen running taskstoo large now
B. Blocking offload onlyone scheduler thread; a pool runs blocking calls (files, DNS, process wait)small; no change to task semanticsuseful, not parallel compute
C. Pinned workersN scheduler threads, each with its own queues; a task stays on its thread; spawn places it by round-robin or a scope settingper-thread state, locked channels, atomic cancel flag and join wordrecommended first
D. C plus stealing of unstarted tasksan idle worker takes a task that has not run yetone extra lock per queuelater, 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.

  1. Per-thread scheduler block. Put the kern_sched_* globals in a struct reached through one reserved register or thread-local slot (arm64 tpidr_el0, x64 fs). The code in conc_*.kn changes from absolute symbols to base-plus-offset.
  2. 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.
  3. Scope. The cancel flag and the child-list join word become atomic. kern_task_join waits with the same inbox signal.
  4. Atomics in the runtime only: ldaxr/stlxr (or LSE casal) on arm64, lock cmpxchg on x64. The language gets no atomic builtin in this step, so no memory-order rules reach user code.
  5. Promise: with threads=N, a program that communicates only through channels gives the same results; only the interleaving of independent tasks changes. The select scan stays in source order.

Files

FileChange
compiler/src/runtime_extra/conc_x64.kn, conc_arm.kn, conc_chan_x64.kn, conc_chan_arm.knper-thread block, locks, inbox, atomic cancel/join
compiler/src/runtime_x64, runtime_arm, runtime_macthread start (clone+futex, pthread_create), idle park and wake
compiler/src/parser/parse.kn, typing/concurrency.kn, backend/concurrency.knscope threads=N
tests/test_parallel.sh, bench/concurrency.pyspeed-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 main is 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=N or an environment setting; is 64 KiB per task (626 MiB for 10,000) enough.

Source: CONCURRENCY-NEXT.md in the repository.