raz / lib / Thread.darwin.raz

192 lines · 6.7 KiB · raw · history · last change 89524972

1(* Threads, for macOS, with Thread.linux-x86_64.raz's interface: made
2 by C's pthread_create, as every program on a Mac uses C. The
3 compiler's entry point finds cCreate and cJoin by name and stores
4 C's pthread_create and pthread_join in them, as on Linux in a
5 program that uses C. Each thread runs on C's stack, of Stack bytes
6 asked for, below which C keeps a page that can't be touched, so
7 that running off the stack stops the program rather than spoiling
8 what lies below; beside it, in a mapping of Thread's own, a little
9 stack for Rt's signal handlers, so that they can say so, and the
10 Thread.
11
12 A Mutex is os_unfair_lock, macOS's lock whose waiters sleep in the
13 kernel, the plainest it supports: __ulock_wait and __ulock_wake,
14 which it is made of, a futex's twins, are not for programs, and
15 pthread_mutex_t needs its initializer. As os_unfair_lock asks, the
16 thread that takes a Mutex gives it up; one that gives up another
17 thread's stops the program.
18
19 Depends on Sys and Rt, and Check for its test. *)
20module Thread;
21import Sys, Rt, Check;
22import SYSTEM;
23
24const
25 Failed*: ERROR = "can't start a thread";
26 Stack = 1 shl 20; (* each thread's, as on Linux without C *)
27 Alt = 65536; (* the signal handlers' stack, more than macOS's least, MINSIGSTKSZ *)
28 Page = 16384; (* arm64 macOS's *)
29
30type
31 (* A thread, as spawn gives it, until join. *)
32 Thread* = record
33 tid: UINT; (* C's pthread_t *)
34 ended: INT; (* 1 once its procedure has returned *)
35 base: ^U8; (* the mapping it is in, the handlers' stack first *)
36 size: INT;
37 fn: proc(arg: ^U8); (* what it runs, and with what *)
38 arg: ^U8;
39 end;
40 (* What sigaltstack takes, as macOS lays it out *)
41 AltStack = record sp: ^U8; size: INT; flags: I32; end;
42 (* A lock whose waiters sleep, free when zeroed: an os_unfair_lock *)
43 Mutex* = record lock: U32; end;
44
45extern proc pthread_attr_init(attr: ^U8): I32;
46extern proc pthread_attr_setstacksize(attr: ^U8; size: UINT): I32;
47extern proc pthread_attr_destroy(attr: ^U8): I32;
48extern proc pthread_kill(t: UINT; sig: I32): I32;
49extern proc sigaltstack(ss, old: ^U8): I32;
50extern proc os_unfair_lock_lock(lock: ^U32);
51extern proc os_unfair_lock_unlock(lock: ^U32);
52
53var
54 (* C's pthread_create and pthread_join, given by the entry point *)
55 cCreate: proc(t: ^UINT; attr: ^U8; start: proc(arg: ^U8): ^U8; arg: ^U8): I32;
56 cJoin: proc(t: UINT; result: ^^U8): I32;
57
58(* Where a new thread starts, as pthread_create calls it: the signal
59 handlers' stack is a thread's own, so it is set here; then the
60 thread runs its procedure, and notes that it has ended, for signal. *)
61proc run(arg: ^U8): ^U8;
62var t: ^Thread; alt: AltStack;
63begin
64 t := ^Thread(arg);
65 alt := {sp: t^.base, size: Alt};
66 _ := sigaltstack(^U8(SYSTEM.ADR(alt)), nil);
67 t^.fn(t^.arg);
68 _ := XCHG(t^.ended, 1);
69 return nil;
70end;
71
72(* Starts p(arg) in a new thread. *)
73proc spawn*(p: proc(arg: ^U8); arg: ^U8): (^Thread, ERROR);
74var base: ^U8; t: ^Thread; size: INT; tid: UINT; attr: [8]U64; r: I32;
75begin
76 size := Alt + Page;
77 base := Sys.mmap(size);
78 if base = nil then return nil, Failed; end;
79 (* the handlers' stack, then the Thread in the last page *)
80 t := ^Thread(base + Alt);
81 t^.base := base;
82 t^.size := size;
83 t^.fn := p;
84 t^.arg := arg;
85 _ := pthread_attr_init(^U8(SYSTEM.ADR(attr)));
86 _ := pthread_attr_setstacksize(^U8(SYSTEM.ADR(attr)), Stack);
87 r := cCreate(SYSTEM.ADR(tid), ^U8(SYSTEM.ADR(attr)), run, ^U8(t));
88 _ := pthread_attr_destroy(^U8(SYSTEM.ADR(attr)));
89 if r # 0 then
90 Sys.munmap(base, size);
91 return nil, Failed;
92 end;
93 t^.tid := tid;
94 return t, nil;
95end;
96
97(* Waits for t to end, then frees what spawn took for it. *)
98proc join*(t: ^Thread);
99var base: ^U8; size: INT;
100begin
101 _ := cJoin(t^.tid, nil);
102 base := t^.base;
103 size := t^.size;
104 Sys.munmap(base, size);
105end;
106
107(* Sends the signal sig to t alone, not to any thread of the program
108 as Sys.kill does: 0, or minus an errno, -3 (ESRCH) if t has ended.
109 With Sys.handle(sig), a system call t waits in fails with -4, so
110 another thread can break into a read. By pthread_kill, whose errnos,
111 ESRCH and EINVAL, are Linux's numbers too. *)
112proc signal*(t: ^Thread; sig: INT): INT;
113begin
114 if XADD(t^.ended, 0) # 0 then return -3; end;
115 return -INT(pthread_kill(t^.tid, I32(sig)));
116end;
117
118(* Takes m, sleeping while another thread holds it. *)
119proc lock*(var m: Mutex);
120begin
121 os_unfair_lock_lock(SYSTEM.ADR(m.lock));
122end;
123
124(* Gives up m, which the calling thread took, waking a thread that
125 waits for it. *)
126proc unlock*(var m: Mutex);
127begin
128 os_unfair_lock_unlock(SYSTEM.ADR(m.lock));
129end;
130
131(* The module's test, and make stress's. It starts n threads, in waves
132 of up to alive at a time, all waiting on one Mutex the test holds
133 until the wave is out; each, given it, adds one to a count. Every
134 thread is joined, so that a stack join didn't free would, over
135 enough of them, run the process out of mappings. With "fail", it
136 starts threads, all waiting, until spawn fails, which it must do
137 with Failed: make stress and make check run it with little memory.
138 Thread [n alive], Thread fail *)
139var
140 testLock: Mutex;
141 testCount: INT;
142 wave: [1000]^Thread;
143
144proc testWork(_arg: ^U8);
145begin
146 lock(testLock);
147 INC(testCount);
148 unlock(testLock);
149end;
150
151proc testArg(i: INT): INT;
152var s: ^U8; n, v: INT;
153begin
154 s := SYSTEM.ARGV()[i];
155 v := 0;
156 n := 0;
157 while s[n] # 0 do v := v * 10 + INT(s[n]) - '0'; INC(n); end;
158 return v;
159end;
160
161(* The module's test: starts threads in waves, and counts that each ran. *)
162proc main*;
163var n, alive, started, k, i: INT; t: ^Thread; err: ERROR; fail: BOOL;
164begin
165 n := 2000; alive := 50;
166 fail := (ARGC() = 2) and (SYSTEM.ARGV()[1][0] = 'f');
167 if ARGC() = 3 then n := testArg(1); alive := testArg(2); end;
168 if fail then n := LEN(wave); alive := LEN(wave); end;
169 if (alive < 1) or (alive > LEN(wave)) then Rt.stop("Thread: alive is 1 to 1000"); end;
170 started := 0;
171 while started < n do
172 lock(testLock);
173 k := 0;
174 while (k < alive) and (started + k < n) do
175 t, err := spawn(testWork, nil);
176 if err # nil then
177 if not fail or (err # Failed) then Rt.stop("Thread.spawn failed"); end;
178 n := started + k;
179 break;
180 end;
181 wave[k] := t;
182 INC(k);
183 end;
184 unlock(testLock);
185 for i := 0 to k - 1 do join(wave[i]); end;
186 started := started + k;
187 end;
188 Check.int("Thread: every thread ran", testCount, started);
189 Check.ok(not (fail and (started = LEN(wave))), "Thread: spawn never failed");
190end;
191
192end Thread.