module Thread; 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. const Failed*: ERROR = "can't start a thread"; type 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; A thread, as spawn gives it, until join. type Mutex* = record state: INT; end; A lock whose waiters sleep, free when zeroed. Its state is 0 free, 1 taken, 2 taken with a thread waiting. proc spawn*(p: proc(arg: ^U8); arg: ^U8): (^Thread, ERROR); Starts p(arg) in a new thread. proc join*(t: ^Thread); Waits for t to end, then frees its stack. proc signal*(t: ^Thread; sig: INT): INT; 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 lock*(var m: Mutex); Takes m, sleeping while another thread holds it. proc unlock*(var m: Mutex); Gives up m, which the caller holds, waking a thread that waits for it. proc main*; The module's test: starts threads in waves, and counts that each ran.