Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

The name of the Erlang registration process


May 13, 2021 Erlang


Table of contents


The name of the Erlang registration process

In the example above, because "Pong" was created before the "ping" process began, the process identifier of the "pong" process can be passed as an argument to the process "ping". T his means that the "ping" process must somehow obtain the process identifier of the "pong" process before the message can be sent to the "pong" process. H owever, in some cases, processes need to start independently of each other, and these processes require to know each other's process identifiers, which is not sufficient in the manner mentioned earlier. T herefore, Erlang provides a name binding mechanism for each process so that inter-process communication can be implemented through the process name without having to know the process identifier of the process. A built-in function register is required to register a name for each process:

register(some_atom, Pid)

Next, let's work together on the ping pong sample program above. T his time, we gave the "pong" process a process name:

-module(tut16).

-export([start/0, ping/1, pong/0]).

ping(0) ->
    pong ! finished,
    io:format("ping finished~n", []);

ping(N) ->
    pong ! {ping, self()},
    receive
        pong ->
            io:format("Ping received pong~n", [])
    end,
    ping(N - 1).

pong() ->
    receive
        finished ->
            io:format("Pong finished~n", []);
        {ping, Ping_PID} ->
            io:format("Pong received ping~n", []),
            Ping_PID ! pong,
            pong()
    end.

start() ->
    register(pong, spawn(tut16, pong, [])),
    spawn(tut16, ping, [3]).
2> c(tut16).
{ok, tut16}
3> tut16:start().
<0.38.0>
Pong received ping
Ping received pong
Pong received ping
Ping received pong
Pong received ping
Ping received pong
ping finished
Pong finished

The start/0 function is as follows:

register(pong, spawn(tut16, pong, [])),

The "pong" process was created along with a name pong. I n the "ping" process, a message is sent as follows:

pong ! {ping, self()},

Ping/2 becomes ping/1. T his is because the parameter Pong_PID no longer needed.