Channels in Elixir

Channels in Elixir are implemented using processes and message passing. You can send values from one process to another using these mechanisms.

defmodule ChannelExample do
  def run do
    # Create a new process that will act as our channel
    pid = spawn(fn -> loop() end)

    # Send a message to the process
    send(pid, {:message, "ping"})

    # Receive the message from the process
    receive do
      {:message, msg} -> IO.puts(msg)
    end
  end

  defp loop do
    receive do
      {:message, msg} -> send(self(), {:message, msg})
    end
    loop()
  end
end

ChannelExample.run()

In this example, we create a new process using spawn/1 that runs the loop/0 function. This process acts as our channel.

We then use send/2 to send a message to the process. This is similar to sending a value into a channel.

The receive block waits for a message to be received. This is analogous to receiving a value from a channel.

When we run the program, the “ping” message is successfully passed from one process to another via our message-passing mechanism.

$ elixir channel_example.exs
ping

By default, receive blocks until a message is available. This property allowed us to wait at the end of our program for the “ping” message without having to use any other synchronization.

In Elixir, this style of concurrent programming using processes and message passing is fundamental to the language and is built on the actor model. It provides a powerful way to build concurrent and distributed systems.