tobogganSe connecter

louise

The Louise language: compiler, runtime, std, tooling

Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.

76 lignes · 2227 octetsBrut · Historique
1import std/io
2import std/process.{type Subject, type proc}
3
4// Selectors receive from several subjects at once, each mapped to one type.
5
6type Event { Number(Int), Word(String) }
7
8fn describe :: e: Event -> String
9{
10 match e { Number(n) -> "number " <> show n, Word(w) -> "word " <> w }
11}
12
13pub fn main :: -> () / <io, proc>
14{
15 let numbers: Subject<Int> = process.subject ()
16 let words: Subject<String> = process.subject ()
17 let selector =
18 process.new_selector ()
19 |> process.selecting numbers fn n { Number(n) }
20 |> process.selecting words fn w { Word(w) }
21 // Messages arrive in this order; select takes the oldest first.
22 {
23 use <- process.spawn
24 process.send words "hello"
25 process.send numbers 42
26 process.send words "bye"
27 }
28 io.println (describe (process.select_forever selector))
29 io.println (describe (process.select_forever selector))
30 io.println (describe (process.select_forever selector))
31 // Nothing more: a timeout gives None.
32 io.println (show (process.select selector 50 |> option_text))
33 // Waiting, then a message arrives on the second subject.
34 {
35 use <- process.spawn
36 process.sleep 10
37 process.send numbers 7
38 }
39 io.println (describe (process.select_forever selector))
40 // A selector on someone else's subject is refused. (A selector holds
41 // functions of its actor, so it cannot be sent: the watcher builds it.)
42 let theirs: Subject<Int> = process.receive_forever (spawn_owner ())
43 let watcher =
44 {
45 use <- process.spawn
46 let other =
47 process.new_selector () |> process.selecting theirs fn n { Number(n) }
48 let _ = process.select other 0
49 ()
50 }
51 let process.Down(_, why) = process.receive_forever (process.monitor watcher)
52 io.println (show why)
53}
54
55fn option_text :: o: Option<Event> -> String
56{
57 match o { Some(e) -> describe e, None -> "nothing" }
58}
59
60/// An actor that creates a subject and hands it back.
61fn spawn_owner :: -> Subject<Subject<Int>> / <proc>
62{
63 let back = process.subject ()
64 {
65 use <- process.spawn
66 process.send back (process.subject ())
67 process.sleep 100000
68 }
69 back
70}
71//> word hello
72//> number 42
73//> word bye
74//> nothing
75//> number 7
76//> Crashed(select on a subject owned by another actor)