← Cookbook Actors and concurrency Beginner · Pooka 0.5.0

A counter actor

A small room with one occupant and a letterbox. Count visitors through a door, from anywhere, without two counts ever colliding.

You will use

  • actor, with a let field fixed at creation and a var field that changes
  • be behaviours: messages that return straight away
  • Ordinary methods: requests that wait for an answer

The whole program

src/main.pooka
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

  1. 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.
  2. be drops a letter in the box. front.arrive() sends a message and returns Nil immediately, without waiting for the count to change.
  3. 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.
  4. Only the actor touches its var. Messages are handled one at a time, in order, so count += 1 can 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.