raz / test / run / ThreadSignalC.raz

51 lines · 1.4 KiB · raw · history · last change 264716cb

1module ThreadSignalC;
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. ThreadSignal is the same, without C. *)
5import Thread, Sys, Fmt, C;
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 if C.getpid() <= 0 then return; end; (* C used, so that Thread makes C's threads *)
26 r, w := Sys.pipe();
27 if Sys.handle(Sys.sigUsr1) # 0 then Fmt.print("no handle\n", []); return; end;
28 t, e := Thread.spawn(reader, nil);
29 if e # nil then Fmt.print("no thread\n", []); return; end;
30 (* again until it lands: the first may come before the read begins *)
31 while (XADD(done, 0) = 0) and (tries < 1000) do
32 k := Thread.signal(t, Sys.sigUsr1);
33 if k # 0 then Fmt.print("signal: {}\n", [Fmt.int(k)]); end;
34 Sys.sleep(5);
35 INC(tries);
36 end;
37 Thread.join(t);
38 Fmt.print("read {}\n", [Fmt.int(got)]);
39 t, e := Thread.spawn(quick, nil);
40 tries := 0;
41 repeat
42 k := Thread.signal(t, 0);
43 Sys.sleep(1);
44 INC(tries);
45 until (k # 0) or (tries = 1000);
46 Thread.join(t);
47 Fmt.print("ended {}\n", [Fmt.int(k)]);
48 Sys.close(w);
49end;
50
51end ThreadSignalC.