4
votes

I was reading this section in "Learn you some Erlang" and there's a piece of code that looks like:

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

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

terminate() ->
?MODULE ! shutdown.

I'm super confused by the terminate function. Does that say to send a message to the module itself? How does that work? What's going on?

1

1 Answers

4
votes

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

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

What specifically is happening in this sample of code is that the process that is being spawned is being registered with the VM under the name of the module so that other processes can refer to it that way. You could replace ?MODULE in that entire block of code with nearly any atom at all, as long as you gave the same value each time.

So when terminate() is invoked, the shutdown message is not sent to the module, but rather to the process that was spawned and been registered under that name with the VM.

Using ?MODULE is merely a convenient approach for avoiding naming conflicts with other registered processes.