(* Threads, made with the clone system call in a program without C. Each runs on a stack of its own, mmaped, with a page below it that can't be touched, so that running off the stack stops the program rather than spoiling what lies below; above it, a little stack for Rt's signal handlers, so that they can say so. join waits on the thread's id, which the kernel clears, and wakes it for, when the thread ends; a Mutex sleeps on a futex. A program that uses C makes them with C's pthread_create instead, since C keeps things of each thread's own, errno and its buffers, that a thread clone makes wouldn't have. The compiler's entry point finds cCreate and cJoin by name and stores C's calls in them, as it stores C's exit in Rt.cExit; so this module uses no C itself, and serves both kinds of program. C's thread has a stack and a guard page of C's; the mapping here holds only the handlers' stack and the Thread. Its test uses Check. *) module Thread; import Sys, Rt, Check; import SYSTEM; const Failed*: ERROR = "can't start a thread"; Stack = 1 shl 20; Alt = 16384; (* the signal handlers' stack *) Page = 4096; (* clone: share memory, files, signal handlers, the thread group; write the id to tid, and clear it at the end *) Flags = 350F00H; FutexWait = 0; FutexWake = 1; Private = 128; type (* A thread, as spawn gives it, until join. *) Thread* = record tid: INT; (* the kernel's id, until the thread ends; or C's pthread_t *) ktid: INT; (* in a C thread, the kernel's id: 0 until it starts, -1 once it ends *) base: ^U8; (* its stack's mapping, the guard page first *) size: INT; fn: proc(arg: ^U8); (* what it runs, and with what *) arg: ^U8; end; (* What sigaltstack takes *) AltStack = record sp: ^U8; flags, size: INT; end; (* A lock whose waiters sleep, free when zeroed. Its state is 0 free, 1 taken, 2 taken with a thread waiting. *) Mutex* = record state: INT; end; var (* C's pthread_create and pthread_join, in a program that uses C; nil in one that doesn't *) cCreate: proc(t: ^UINT; attr: ^U8; start: proc(arg: ^U8): ^U8; arg: ^U8): I32; cJoin: proc(t: UINT; result: ^^U8): I32; (* clone(flags, stack, tid, tid), the new thread starting with fn(arg) on stack and ending, when fn returns, with the exit system call. fn and arg go on the new stack first, since the new thread has no registers but rsp of its own to find them by. Returns the new thread's id, or minus an errno. *) proc start(flags: INT; stack: ^U8; ptid, ctid: ^INT; fn: proc(arg: ^U8); arg: ^U8): INT; code sub rsi, 16; mov [rsi], r8; mov [rsi + 8], r9; mov r10, rcx; xor r8d, r8d; (* no tls *) mov eax, 56; (* clone *) syscall; test rax, rax; jnz parent; pop rax; (* fn *) pop rdi; (* arg *) xor ebp, ebp; (* the first frame: Rt's report of the calls stops here *) call rax; xor edi, edi; mov eax, 60; (* exit, this thread only *) syscall; parent: ret; end start; proc futex(word: ^INT; op, val: INT): INT; begin return SYSTEM.SYSCALL(202, word, op, val, 0); end; (* Where a new thread starts: the signal handlers' stack is a thread's own, so it is set here, below t; then the thread runs its procedure. *) proc run(arg: ^U8); var t: ^Thread; alt: AltStack; begin t := ^Thread(arg); alt := {sp: ^U8(t) - Alt, size: Alt}; _ := SYSTEM.SYSCALL(131, SYSTEM.ADR(alt), 0); (* sigaltstack *) t^.fn(t^.arg); end; (* Where a thread C makes starts, as pthread_create calls it. C keeps the kernel's id of its thread to itself, so the thread notes its own, for signal, and marks it gone as it ends. *) proc cRun(arg: ^U8): ^U8; var t: ^Thread; begin t := ^Thread(arg); _ := XCHG(t^.ktid, SYSTEM.SYSCALL(186)); (* gettid *) run(arg); _ := XCHG(t^.ktid, -1); return nil; end; (* Starts p(arg) in a new thread. *) proc spawn*(p: proc(arg: ^U8); arg: ^U8): (^Thread, ERROR); var base: ^U8; t: ^Thread; size: INT; tid: UINT; begin size := Page + Stack + Alt + Page; if cCreate # nil then size := Alt + Page; end; (* C gives the stack *) base := Sys.mmap(size); if base = nil then return nil, Failed; end; (* from the top: the Thread in the last page, the handlers' stack, then the thread's, starting on a page *) t := ^Thread(base + size - Page); t^.base := base; t^.size := size; t^.fn := p; t^.arg := arg; if cCreate # nil then if cCreate(SYSTEM.ADR(tid), nil, cRun, ^U8(t)) # 0 then Sys.munmap(base, size); return nil, Failed; end; t^.tid := INT(tid); return t, nil; end; (* mprotect: the guard page, no access; it fails when the process has as many mappings as it may *) if (SYSTEM.SYSCALL(10, base, Page, 0) < 0) or (start(Flags, base + Page + Stack, SYSTEM.ADR(t^.tid), SYSTEM.ADR(t^.tid), run, ^U8(t)) < 0) then Sys.munmap(base, size); return nil, Failed; end; return t, nil; end; (* Waits for t to end, then frees its stack. *) proc join*(t: ^Thread); var tid: ^VOLATILE INT; v: INT; base: ^U8; size: INT; begin if cJoin # nil then _ := cJoin(UINT(t^.tid), nil); else tid := SYSTEM.ADR(t^.tid); v := tid^; while v # 0 do _ := futex(SYSTEM.ADR(t^.tid), FutexWait, v); v := tid^; end; end; base := t^.base; size := t^.size; Sys.munmap(base, size); end; (* Sends the signal sig to t alone, not to any thread of the program as Sys.kill does: 0, or minus an errno, -3 (ESRCH) if t has ended. With Sys.handle(sig), a system call t waits in fails with -4, so another thread can break into a read. tgkill, in a program with C too, since pthread_kill is tgkill with C's id for the thread: a C thread that hasn't noted its id yet is waited for. *) proc signal*(t: ^Thread; sig: INT): INT; var tid: ^VOLATILE INT; k: INT; begin if cCreate # nil then tid := SYSTEM.ADR(t^.ktid); k := tid^; while k = 0 do Sys.yield; k := tid^; end; else tid := SYSTEM.ADR(t^.tid); k := tid^; end; if k <= 0 then return -3; end; return SYSTEM.SYSCALL(234, Sys.pid(), k, sig); (* tgkill *) end; (* Takes m, sleeping while another thread holds it. *) proc lock*(var m: Mutex); var c: INT; begin if CAS(m.state, 0, 1) then return; end; c := XCHG(m.state, 2); while c # 0 do _ := futex(SYSTEM.ADR(m.state), FutexWait + Private, 2); c := XCHG(m.state, 2); end; end; (* Gives up m, which the caller holds, waking a thread that waits for it. *) proc unlock*(var m: Mutex); begin if XADD(m.state, -1) # 1 then _ := XCHG(m.state, 0); _ := futex(SYSTEM.ADR(m.state), FutexWake + Private, 1); end; end; (* The module's test, and make stress's. It starts n threads, in waves of up to alive at a time, all waiting on one Mutex the test holds until the wave is out; each, given it, adds one to a count. Every thread is joined, so that a stack join didn't free would, over enough of them, run the process out of mappings. With "fail", it starts threads, all waiting, until spawn fails, which it must do with Failed: make stress and make check run it with little memory. Thread [n alive], Thread fail *) var testLock: Mutex; testCount: INT; wave: [1000]^Thread; proc testWork(_arg: ^U8); begin lock(testLock); INC(testCount); unlock(testLock); end; proc testArg(i: INT): INT; var s: ^U8; n, v: INT; begin s := SYSTEM.ARGV()[i]; v := 0; n := 0; while s[n] # 0 do v := v * 10 + INT(s[n]) - '0'; INC(n); end; return v; end; (* The module's test: starts threads in waves, and counts that each ran. *) proc main*; var n, alive, started, k, i: INT; t: ^Thread; err: ERROR; fail: BOOL; begin n := 2000; alive := 50; fail := (ARGC() = 2) and (SYSTEM.ARGV()[1][0] = 'f'); if ARGC() = 3 then n := testArg(1); alive := testArg(2); end; if fail then n := LEN(wave); alive := LEN(wave); end; if (alive < 1) or (alive > LEN(wave)) then Rt.stop("Thread: alive is 1 to 1000"); end; started := 0; while started < n do lock(testLock); k := 0; while (k < alive) and (started + k < n) do t, err := spawn(testWork, nil); if err # nil then if not fail or (err # Failed) then Rt.stop("Thread.spawn failed"); end; n := started + k; break; end; wave[k] := t; INC(k); end; unlock(testLock); for i := 0 to k - 1 do join(wave[i]); end; started := started + k; end; Check.int("Thread: every thread ran", testCount, started); Check.ok(not (fail and (started = LEN(wave))), "Thread: spawn never failed"); end; end Thread.