| 1 | module 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; this copy runs over |
| 5 | the C library's Sys. *) |
| 6 | import Thread, Sys, Fmt, C; |
| 7 | import SYSTEM; |
| 8 | |
| 9 | var |
| 10 | r, got, done: INT; |
| 11 | |
| 12 | proc reader(_arg: ^U8); |
| 13 | var buf: [16]U8; |
| 14 | begin |
| 15 | got := Sys.read(r, buf); |
| 16 | _ := XCHG(done, 1); |
| 17 | end; |
| 18 | |
| 19 | proc quick(_arg: ^U8); |
| 20 | begin |
| 21 | end; |
| 22 | |
| 23 | proc main*; |
| 24 | var t: ^Thread.Thread; e: ERROR; w, tries, k: INT; |
| 25 | begin |
| 26 | if C.getpid() <= 0 then return; end; (* C used, so that Thread makes C's threads *) |
| 27 | r, w := Sys.pipe(); |
| 28 | if Sys.handle(Sys.sigUsr1) # 0 then Fmt.print("no handle\n", []); return; end; |
| 29 | t, e := Thread.spawn(reader, nil); |
| 30 | if e # nil then Fmt.print("no thread\n", []); return; end; |
| 31 | (* again until it lands: the first may come before the read begins *) |
| 32 | while (XADD(done, 0) = 0) and (tries < 1000) do |
| 33 | k := Thread.signal(t, Sys.sigUsr1); |
| 34 | if k # 0 then Fmt.print("signal: {}\n", [Fmt.int(k)]); end; |
| 35 | Sys.sleep(5); |
| 36 | INC(tries); |
| 37 | end; |
| 38 | Thread.join(t); |
| 39 | Fmt.print("read {}\n", [Fmt.int(got)]); |
| 40 | t, e := Thread.spawn(quick, nil); |
| 41 | tries := 0; |
| 42 | repeat |
| 43 | k := Thread.signal(t, 0); |
| 44 | Sys.sleep(1); |
| 45 | INC(tries); |
| 46 | until (k # 0) or (tries = 1000); |
| 47 | Thread.join(t); |
| 48 | Fmt.print("ended {}\n", [Fmt.int(k)]); |
| 49 | Sys.close(w); |
| 50 | end; |
| 51 | |
| 52 | end ThreadSignalC. |