// Timers: actors that wait with timeouts, on all threads. // - 1,000 client/server pairs make 100 calls each, both sides receiving // with a timeout that never expires (a `call` with a timeout); // - 1,000 actors sleep 1 ms, 50 times each; // - 1,000 actors wait 1 ms for a message that never comes, 50 times each. import std/io import std/process.{type Subject, type proc} fn server :: inbox: Subject<(Int, Subject)> n: Int -> () / { if n > 0 { match process.receive inbox 60000 { Some((x, reply)) -> { process.send reply (x + 1) server inbox (n - 1) } , None -> panic "server: timed out" } } } fn client :: server: Subject<(Int, Subject)> reply: Subject n: Int acc: Int -> Int / { if n == 0 { acc } else { process.send server (n, reply) match process.receive reply 60000 { Some(x) -> client server reply (n - 1) (acc + x) , None -> panic "client: timed out" } } } fn sleeper :: n: Int -> Int / { if n == 0 { 0 } else { process.sleep 1 1 + sleeper (n - 1) } } fn waiter :: quiet: Subject n: Int -> Int / { if n == 0 { 0 } else { match process.receive quiet 1 { Some(_) -> panic "waiter: a message", None -> 1 + waiter quiet (n - 1) } } } fn spawn_pairs :: n: Int done: Subject -> () / { if n > 0 { let _ = process.spawn fn { let ready = process.subject () let _ = process.spawn fn { let inbox = process.subject () process.send ready inbox server inbox 100 } let inbox = process.receive_forever ready process.send done (client inbox (process.subject ()) 100 0) } spawn_pairs (n - 1) done } } fn spawn_sleepers :: n: Int done: Subject -> () / { if n > 0 { let _ = process.spawn fn { process.send done (sleeper 50) } let _ = process.spawn fn { process.send done (waiter (process.subject ()) 50) } spawn_sleepers (n - 1) done } } fn sum :: done: Subject left: Int total: Int -> Int / { if left == 0 { total } else { sum done (left - 1) (total + process.receive_forever done) } } pub fn main :: -> () / { let done = process.subject () spawn_pairs 1000 done spawn_sleepers 1000 done io.println (show (sum done 3000 0)) } //> 5250000