| @@ -0,0 +1,59 @@ |
| 1 | +// Selective receive under unrelated traffic: `main` makes 50,000 calls, |
| 2 | +// each waiting for its reply on a subject of its own, while 4 actors keep |
| 3 | +// sending to its other subject. A message a receive does not wait for may |
| 4 | +// wake it (ADR 0028); it then waits again. |
| 5 | +import std/io |
| 6 | +import std/process.{type proc, type Subject} |
| 7 | + |
| 8 | +fn server(requests: Subject<Subject<Int>>, n: Int) -> () / <proc> { |
| 9 | + let reply = process.receive_forever(requests) |
| 10 | + process.send(reply, n) |
| 11 | + server(requests, n + 1) |
| 12 | +} |
| 13 | + |
| 14 | +fn flood(to: Subject<Int>, n: Int) -> () / <proc> { |
| 15 | + if n > 0 { |
| 16 | + process.send(to, n) |
| 17 | + flood(to, n - 1) |
| 18 | + } |
| 19 | +} |
| 20 | + |
| 21 | +fn calls(requests: Subject<Subject<Int>>, n: Int, total: Int) -> Int / <proc> { |
| 22 | + if n == 0 { |
| 23 | + total |
| 24 | + } else { |
| 25 | + let reply = process.subject() |
| 26 | + process.send(requests, reply) |
| 27 | + calls(requests, n - 1, total + process.receive_forever(reply)) |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +fn drain(from: Subject<Int>, left: Int, total: Int) -> Int / <proc> { |
| 32 | + if left == 0 { |
| 33 | + total |
| 34 | + } else { |
| 35 | + drain(from, left - 1, total + process.receive_forever(from)) |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +fn spawn_floods(k: Int, to: Subject<Int>) -> () / <proc> { |
| 40 | + if k > 0 { |
| 41 | + let _ = process.spawn(fn() { flood(to, 50000) }) |
| 42 | + spawn_floods(k - 1, to) |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +pub fn main() -> () / <io, proc> { |
| 47 | + let ready = process.subject() |
| 48 | + let noise = process.subject() |
| 49 | + let _ = process.spawn(fn() { |
| 50 | + let requests = process.subject() |
| 51 | + process.send(ready, requests) |
| 52 | + server(requests, 0) |
| 53 | + }) |
| 54 | + let requests = process.receive_forever(ready) |
| 55 | + spawn_floods(4, noise) |
| 56 | + let replies = calls(requests, 50000, 0) |
| 57 | + io.println(show(replies) <> " " <> show(drain(noise, 4 * 50000, 0))) |
| 58 | +} |
| 59 | +//> 1249975000 5000100000 |