9 Concurrency Basics

9.1 Processes

How can processes communicate with each other to share data? We can use send to send data to a specific process, and receive to retrieve data from a a specific process.

9.2 Managing State with Long-lived Processes

defmodule Counter do
  # public API
  def start_link(initial_count \\ 0) do
    spawn_link(Counter, :run, [initial_count])
  end

  def increment(pid) when is_pid(pid) do
    send(pid, :increment)
  end

  def decrement(pid) when is_pid(pid) do
    send(pid, :decrement)
  end

  def count(pid) when is_pid(pid) do
    send(pid, {:count, self()})

    receive do
      {^pid, count} -> count
    end
  end

  # implementation
  def run(count) do
    receive do
      msg -> handler(msg, count)
    end
    |> run()
  end

  def handler(:increment, count), do: count + 1
  def handler(:decrement, count), do: count - 1

  def handler({:count, pid}, count) do
    send(pid, {self(), count})
    count
  end
end
iex(1)> import Counter
iex(2)> p = start_link()
#PID<0.112.0>
iex(3)> increment(p)
#> :increment
iex(4)> increment(p)
#> :increment
iex(5)> increment(p)
#> :increment
iex(6)> count(p)
#> 3

9.3 Supervisor

9.4 Basic HTTP Server