Channels in Erlang
In Erlang, we use processes and message passing to achieve concurrency. This is similar to channels in other languages. Here’s how we can implement a simple message passing example:
In this Erlang code:
We define a module called
channels
with astart/0
function.In the
start/0
function, we spawn a new process usingspawn(fun() -> send_message() end)
. This is similar to creating a new goroutine in other languages.The
send_message/0
function sends a message"ping"
to the parent process using the!
operator. This is equivalent to sending a value into a channel.Back in the
start/0
function, we use thereceive
construct to wait for and receive the message. This is similar to receiving from a channel.When the message is received, we print it using
io:format/2
.
To run the program:
In this example, the “ping” message is successfully passed from one process to another via Erlang’s built-in message passing mechanism.
By default, Erlang’s message passing is asynchronous, but the receive
construct allows us to wait for a message, providing synchronization similar to channel communication in other languages.
This demonstrates how Erlang’s processes and message passing can be used to achieve similar functionality to channels in concurrent programming.