// Message passing: a ring of actors passing a token, on all threads. import std/io import std/process.{type Subject, type proc} fn relay :: inbox: Subject next: Subject -> () / { let token = process.receive_forever inbox process.send next (token + 1) relay inbox next } fn laps :: start: Subject back: Subject n: Int token: Int -> Int / { if n == 0 { token } else { process.send start token laps start back (n - 1) (process.receive_forever back) } } pub fn main :: -> () / { let back = process.subject () let ready = process.subject () let _ = process.spawn fn { let inbox = process.subject () process.send ready inbox relay inbox back } let last = process.receive_forever ready // The ring is built backwards: each new actor forwards to the previous // one, and the first to `back`. Relays run until `main` stops. let start = ring_from 999 last io.println (show (laps start back 200 0)) } fn ring_from :: size: Int next: Subject -> Subject / { if size == 0 { next } else { let ready = process.subject () let _ = process.spawn fn { let inbox = process.subject () process.send ready inbox relay inbox next } ring_from (size - 1) (process.receive_forever ready) } } //> 200000