Erlang: send message to module?

I read this section under "Find out you have Erlang" and there is a piece of code that looks like this:

start() ->
register(?MODULE, Pid=spawn(?MODULE, init, [])),
Pid.

start_link() ->
register(?MODULE, Pid=spawn_link(?MODULE, init, [])),
Pid.

terminate() ->
?MODULE ! shutdown.

      

The function confuses me terminate

. Does that tell you to send the message to the module itself? How it works? What's happening?

+3


source to share


1 answer


TL; DR: The shutdown is sent to the process, not the module.

? MODULE is a value that is changed at compile time to the name of the current module (file).

What exactly happens in this code example: The process that is created is registered with the virtual machine under the module name so that other processes can refer to it in this way. You can replace MODULE in the whole block of code with almost any atom as long as you gave the same value every time.



Thus, when the terminate () function is called, the shutdown message is not sent to the module, but rather to the process that was spawned and registered under that name with the virtual machine.

Using? MODULE is simply a convenient approach to avoid name collisions with other registered processes.

+3


source







All Articles