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:

  1. We define a module called channels with a start/0 function.

  2. In the start/0 function, we spawn a new process using spawn(fun() -> send_message() end). This is similar to creating a new goroutine in other languages.

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

  4. Back in the start/0 function, we use the receive construct to wait for and receive the message. This is similar to receiving from a channel.

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

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.

查看推荐产品

Comments powered by Disqus