raz / test / run / ThreadSignal.raz

50 lines · 1.3 KiB · raw · history · last change 264716cb

1module ThreadSignal;
2(* Thread.signal breaks into a read one thread waits in, the signal
3 handled: the read fails with -4. A thread that has ended, not yet
4 joined, is -3. ThreadSignalC is the same, over C. *)
5import Thread, Sys, Fmt;
6import SYSTEM;
7
8var
9 r, got, done: INT;
10
11proc reader(_arg: ^U8);
12var buf: [16]U8;
13begin
14 got := Sys.read(r, buf);
15 _ := XCHG(done, 1);
16end;
17
18proc quick(_arg: ^U8);
19begin
20end;
21
22proc main*;
23var t: ^Thread.Thread; e: ERROR; w, tries, k: INT;
24begin
25 r, w := Sys.pipe();
26 if Sys.handle(Sys.sigUsr1) # 0 then Fmt.print("no handle\n", []); return; end;
27 t, e := Thread.spawn(reader, nil);
28 if e # nil then Fmt.print("no thread\n", []); return; end;
29 (* again until it lands: the first may come before the read begins *)
30 while (XADD(done, 0) = 0) and (tries < 1000) do
31 k := Thread.signal(t, Sys.sigUsr1);
32 if k # 0 then Fmt.print("signal: {}\n", [Fmt.int(k)]); end;
33 Sys.sleep(5);
34 INC(tries);
35 end;
36 Thread.join(t);
37 Fmt.print("read {}\n", [Fmt.int(got)]);
38 t, e := Thread.spawn(quick, nil);
39 tries := 0;
40 repeat
41 k := Thread.signal(t, 0);
42 Sys.sleep(1);
43 INC(tries);
44 until (k # 0) or (tries = 1000);
45 Thread.join(t);
46 Fmt.print("ended {}\n", [Fmt.int(k)]);
47 Sys.close(w);
48end;
49
50end ThreadSignal.