Elixir Global Names
A global name is a name that identifies one process across nodes. This lesson proves the naming rules on one node, since a real cluster is needed to prove lookup on another node.
A global name claims a process
:global.register_name() gives a process a name known across nodes. Registering the current process returns :yes.
IO.inspect(:global.register_name(:greeter, self()))
IO.inspect(:global.whereis_name(:greeter) == self())A taken name refuses a second claim
A name can belong to only one process at a time. A second claim returns :no, even from the same process.
:global.register_name(:greeter, self())
IO.inspect(:global.register_name(:greeter, self()))Removing a name frees it
:global.unregister_name() removes a name. After removal, looking the name up returns :undefined.
:global.register_name(:greeter, self())
IO.inspect(:global.unregister_name(:greeter))
IO.inspect(:global.whereis_name(:greeter))Example
:global.register_name(:greeter, self())
pid = :global.whereis_name(:greeter)
send(pid, {:greet, "hello"})
receive do
{:greet, text} -> IO.inspect(text)
end
:global.unregister_name(:greeter)Key points
- :global.register_name(): gives a process a name that any node can look up.
- :global.whereis_name(): returns the process for a name, or :undefined when the name is free.
- One owner: a name belongs to one process at a time, so a second claim returns :no.
- Unregister: :global.unregister_name() frees a name for a new claim.
- Message: a looked-up process can receive a message like any process.
In this example, the script registers the current process under a name, looks that name up, sends a greeting to the looked-up process, and receives the greeting. The name is removed at the end.
Note
a real cluster is needed to prove a name resolves on another node, and this lesson proves only the single-node mechanics.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does :global.register_name(:greeter, self()) return when :greeter is free?