GitHub

title Concurrent Prime Factorization
subtitle A Go Programmer Learns Elixir Concurrency
author Patrick Bucher, Composed GmbH

The concurrency model used in Elixir (and Erlang), often referred to as the Actor Model, is quite similar to the model used in Go, which is called Communicating Sequential Processes. There are many things in common, indeed:

  • Both Elixir's (or Erlang's) processes and Go's goroutines are lightweight. It's practical to have hundreds or even thousands of them running, which are mapped to operating system threads in a n:m manner (n OS threads running m processes/goroutines).
  • Both models facilitate message passing between concurrent units of execution (processes/goroutines).
  • Both languages offer language constructs for dealing with incoming messages: receive in Elixir, select/case and the arrow operator <- in Go.

However, there are a few important differences, which may make a programmer coming over from Go (or a language solely using a shared-memory and thread-based model like Java, for that matter) to Elixir struggle:

  • In Elixir, processes do not share memory, whereas Go offers facilities for both concurrency styles—message passing and shared memory.
  • Elixir's spawn/1 function starts a new process and returns a process identifier (PID), whereas Go's go keyword creates and starts a new goroutine and returns nothing.
  • Knowing a process's PID is sufficient to send a message to it in Elixir, whereas in Go channels known to both goroutines are required for communication between them.
  • As a consequence, a goroutine can wait for a message from a specific channel (possibly only known to another specific goroutine), whereas in Elixir a process can just wait for any incoming message being sent from any other process.
  • Implementing a message loop in Elixir requires (tail) recursion, whereas Go uses (infinite) loops.
  • Being a dynamically typed language, incoming messages are matched against patterns in Elixir, whereas Go uses typed channels, which deliver messages of the same type and shape.

Having worked with Go's model, the author's goal is to become acquainted wich Elixir's model by solving the problem stated below.

Problem

Natural numbers can be expressed as a product of prime numbers. For example, 12 is the product of 2, 2, and 3, whereas 13, which is a prime number itself, is the product of 13 (and the neutral element 1, which is not a prime number). A few examples:

Number Prime Factors Check

Read the original on github.com ↗