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.
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.
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.