← Cookbook Actors and concurrency Intermediate · Pooka 0.5.0

Fan work out to actors

Split a big sum into four parts, give each to its own actor so they work at the same time, then collect the answers.

You will use

  • An actor with a be behaviour for the work and a method for the result
  • pooka/list: range, map, fold

The whole program

src/main.pooka
module main

import pooka/int
import pooka/io
import pooka/list

/// Adds up the squares of a range of numbers, in its own process.
actor Worker {
  var total: Int = 0

  be sum_squares(from: Int, to: Int) {
    // `list.range` stops before its end, so ask for one more.
    total = list.fold(list.range(from, to + 1), 0, fn(acc: Int, n: Int) {
      acc + n * n
    })
  }

  result() -> Int {
    total
  }
}

main() {
  // Four workers, a quarter of the numbers each.
  let ranges = [#(1, 250000), #(250001, 500000), #(500001, 750000), #(
    750001,
    1000000
  )]
  let workers = list.map(ranges, fn(range: #(Int, Int)) {
    let worker = Worker()
    worker.sum_squares(range.0, range.1)
    worker
  })

  // Asking for a result waits until that worker has done its sum.
  let parts = list.map(workers, fn(worker: Worker) { worker.result() })
  let total = list.fold(parts, 0, fn(acc: Int, part: Int) { acc + part })
  io.println("parts: " + int.to_string(list.length(parts)))
  io.println("total: " + int.to_string(total))
}

Run it

$ pooka run
parts: 4
total: 333333833333500000

That is the sum of the squares of every number from one to a million, which the formula n(n+1)(2n+1)/6 agrees with.

How it works

  1. Hand out the work. The first list.map creates a Worker for each range and sends it sum_squares. Because that is a be behaviour, sending returns at once, and all four workers start computing side by side, on as many cores as the BEAM has.
  2. Collect the answers. The second list.map asks each worker for result(). A request waits until the worker has handled the messages sent before it, so each answer is the finished sum.
  3. Add them up. A fold combines the four parts into the total.
  4. Mind the range. list.range(from, to) stops before to, so the worker asks for to + 1 to include its last number.

Try next: time it with time.monotonic_now() and time.duration_between, then compare with one worker doing the whole range.