You will use
actor, with aletfield fixed at creation and avarfield that changesbebehaviours: messages that return straight away- Ordinary methods: requests that wait for an answer
The whole program
module main
import pooka/int
import pooka/io
actor Visitors {
let door: String
var count: Int
new(door: String) {
self.door = door
self.count = 0
}
be arrive() {
count += 1
}
be arrive_together(group: Int) {
count += group
}
be reset() {
count = 0
}
report() -> String {
int.to_string(count) + " visitors through the " + door
}
}
main() {
let front = Visitors("front door")
front.arrive()
front.arrive_together(3)
front.arrive()
io.println(front.report())
front.reset()
io.println(front.report())
}
Run it
$ pooka run
5 visitors through the front door
0 visitors through the front door
How it works
- Creating an actor starts a process.
Visitors("front door")starts a new BEAM process for the actor and hands you a way to reach it. bedrops a letter in the box.front.arrive()sends a message and returnsNilimmediately, without waiting for the count to change.- Methods ask and wait.
front.report()is a request: it waits in line behind the messages sent before it, then answers. That is why it sees all five arrivals. - Only the actor touches its
var. Messages are handled one at a time, in order, socount += 1can never be interrupted halfway by another visitor.
An actor is a small room with one occupant and a letterbox. You cannot go in. You can only write.
Try next: give the actor a with interface, so code that only needs report() can accept any kind of counter. Fan work out to actors uses several at once.