raz / test / doc / Thread.expect

57 lines · 2.4 KiB · raw · history · last change 280d4d6f

1module Thread;
2 Threads, made with the clone system call in a program without C.
3 Each runs on a stack of its own, mmaped, with a page below it that
4 can't be touched, so that running off the stack stops the program
5 rather than spoiling what lies below; above it, a little stack for
6 Rt's signal handlers, so that they can say so. join waits on the
7 thread's id, which the kernel clears, and wakes it for, when the
8 thread ends; a Mutex sleeps on a futex.
9
10 A program that uses C makes them with C's pthread_create instead,
11 since C keeps things of each thread's own, errno and its buffers,
12 that a thread clone makes wouldn't have. The compiler's entry point
13 finds cCreate and cJoin by name and stores C's calls in them, as it
14 stores C's exit in Rt.cExit; so this module uses no C itself, and
15 serves both kinds of program. C's thread has a stack and a guard
16 page of C's; the mapping here holds only the handlers' stack and
17 the Thread. Its test uses Check.
18
19const Failed*: ERROR = "can't start a thread";
20
21type Thread* = record
22 tid: INT; (* the kernel's id, until the thread ends; or C's pthread_t *)
23 ktid: INT; (* in a C thread, the kernel's id: 0 until it starts, -1 once it ends *)
24 base: ^U8; (* its stack's mapping, the guard page first *)
25 size: INT;
26 fn: proc(arg: ^U8); (* what it runs, and with what *)
27 arg: ^U8;
28end;
29 A thread, as spawn gives it, until join.
30
31type Mutex* = record state: INT; end;
32 A lock whose waiters sleep, free when zeroed. Its state is 0
33 free, 1 taken, 2 taken with a thread waiting.
34
35proc spawn*(p: proc(arg: ^U8); arg: ^U8): (^Thread, ERROR);
36 Starts p(arg) in a new thread.
37
38proc join*(t: ^Thread);
39 Waits for t to end, then frees its stack.
40
41proc signal*(t: ^Thread; sig: INT): INT;
42 Sends the signal sig to t alone, not to any thread of the program
43 as Sys.kill does: 0, or minus an errno, -3 (ESRCH) if t has ended.
44 With Sys.handle(sig), a system call t waits in fails with -4, so
45 another thread can break into a read. tgkill, in a program with C
46 too, since pthread_kill is tgkill with C's id for the thread: a C
47 thread that hasn't noted its id yet is waited for.
48
49proc lock*(var m: Mutex);
50 Takes m, sleeping while another thread holds it.
51
52proc unlock*(var m: Mutex);
53 Gives up m, which the caller holds, waking a thread that waits
54 for it.
55
56proc main*;
57 The module's test: starts threads in waves, and counts that each ran.