forked from nulang-org/nulang
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshared_counter.nula
More file actions
63 lines (48 loc) · 1.3 KB
/
Copy pathshared_counter.nula
File metadata and controls
63 lines (48 loc) · 1.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// Shared Counter — distributed counter via actor messaging.
// Multiple worker actors increment a shared counter held by a
// coordinator. Demonstrates request-response patterns between
// actors using the `!` send operator and behavior dispatch.
//
// Run with: nulang examples/shared_counter.nula
actor Counter {
state value: Int = 0
behavior increment(amount: Int) {
self.value = self.value + amount
}
behavior decrement(amount: Int) {
self.value = self.value - amount
}
behavior read() {
perform IO.print(
"Counter value: " + perform Int.to_string(self.value)
)
}
}
actor Worker {
state counter_ref: Int = 0
state name: String = "anon"
behavior init(name_str: String, counter: Int) {
self.name = name_str
self.counter_ref = counter
}
behavior do_inc(amount: Int) {
self.counter_ref ! increment(amount)
}
behavior do_dec(amount: Int) {
self.counter_ref ! decrement(amount)
}
}
fn main() {
let counter = spawn Counter {}
let w1 = spawn Worker {}
let w2 = spawn Worker {}
w1 ! init("alice", counter)
w2 ! init("bob", counter)
w1 ! do_inc(10)
w2 ! do_inc(5)
w1 ! do_dec(3)
counter ! read()
w2 ! do_inc(42)
counter ! read()
0
}