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:
-module(channels).
-export([start/0]).
start() ->
% Spawn a new process that will send a message
Pid = spawn(fun() -> send_message() end),
% Receive the message from the spawned process
receive
{message, Msg} ->
io:format("~p~n", [Msg])
end.
send_message() ->
% Send a message to the parent process
Parent = self(),
Parent ! {message, "ping"}.In this Erlang code:
We define a module called
channelswith astart/0function.In the
start/0function, we spawn a new process usingspawn(fun() -> send_message() end). This is similar to creating a new goroutine in other languages.The
send_message/0function 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/0function, we use thereceiveconstruct 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:
$ erlc channels.erl
$ erl -noshell -s channels start -s init stop
pingIn 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.
Comments powered by Disqus