raz / sbcl / lib / Thread.raz

60 lines · 1.2 KiB · raw · history · last change 55bc6c0d

1(* Threads for a program without C: spawn, join, and Mutex. Here each is a
2 thread of SBCL's, on a raz stack of its own. *)
3module Thread;
4import Heap, Mem;
5link static;
6
7const Failed*: ERROR = "can't start a thread";
8
9type
10 Thread* = record id: INT; end;
11 Mutex* = record state: INT; end; (* zero is free; 1 taken; 2 taken, with waiters *)
12
13const
14 sysFutex = 202;
15 futexWait = 128; (* FUTEX_WAIT, private *)
16 futexWake = 129;
17
18proc start(p: proc(arg: ^U8); arg: ^U8): INT;
19code
20 (thread-spawn p arg);
21end;
22
23proc wait(id: INT);
24code
25 (thread-join id);
26end;
27
28(* p(arg) in a new thread *)
29proc spawn*(p: proc(arg: ^U8); arg: ^U8): (^Thread, ERROR);
30var t: ^Thread;
31begin
32 NEW(t, Heap.heap);
33 if t = nil then return nil, Failed; end;
34 t^.id := start(p, arg);
35 return t, nil;
36end;
37
38(* waits for t to end, then frees what it had *)
39proc join*(t: ^Thread);
40begin
41 wait(t^.id);
42 Mem.free(Heap.heap, ^U8(t));
43end;
44
45proc lock*(m: ^Mutex);
46begin
47 if CAS(ADR(m^.state), 0, 1) then return; end;
48 while XCHG(ADR(m^.state), 2) # 0 do
49 _ := SYSCALL(sysFutex, ADR(m^.state), futexWait, 2, 0);
50 end;
51end;
52
53proc unlock*(m: ^Mutex);
54begin
55 if XCHG(ADR(m^.state), 0) = 2 then
56 _ := SYSCALL(sysFutex, ADR(m^.state), futexWake, 1);
57 end;
58end;
59
60end Thread.