全局进程注册
管理全局进程名称,并在分布式 Erlang 集群中发现进程,以协调各项操作。
全局进程注册 是 CoddyKit 上的免费 Erlang OTP: Distributed & Fault-Tolerant Systems Programming 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Erlang OTP: Distributed & Fault-Tolerant Systems Programming 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Erlang OTP: Distributed & Fault-Tolerant Systems Programming 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Global Names Across Nodes
In distributed Erlang, processes often need to find each other, even if they're on different machines. How do you find a process when you don't know which node it lives on?
Erlang's global module provides a solution: global process registration. It allows you to give a process a unique name that is known across all connected nodes in your cluster.
Local vs. Global Processes
Normally, when you register a process using register/2, its name is only known on the local node. If my_process is on nodeA@host, a process on nodeB@host can't find it just by its name.
Global registration solves this! It acts like a distributed directory service. Any process on any connected node can look up a globally registered name and get the corresponding Process ID (PID), regardless of where that process is running.
`global:register_name/2`
To make a process accessible globally, you use global:register_name(Name, Pid).
Name: An atom that will be the unique global name (e.g.,my_service).Pid: The Process ID of the process you want to register.
If the name is already taken, register_name returns {false, OldPid}, otherwise true. The global module ensures that a global name is unique across the entire distributed cluster.
`global:whereis_name/1`
Once a process is registered, any other process can find it using global:whereis_name(Name).
Name: The global name (atom) you're looking for.
This function returns the PID of the registered process if found, or the atom undefined if no process is registered under that name.
It's crucial to check for undefined before attempting to send messages to the returned PID.
Full Global Communication Demo
This runnable example brings it all together! A server process starts and registers itself globally. After a short delay, a client process then finds this global server and sends it a message, receiving a reply.
Observe how global:register_name ensures the server is known, and global:whereis_name allows the client to locate it, enabling seamless communication.
-module(global_demo).
-export([main/0]).
% Server Functions
server_init() ->
case global:register_name(my_global_service, self()) of
true ->
io:format("Server (~p) registered as my_global_service~n", [self()]),
server_loop();
{false, OldPid} ->
io:format("Error: my_global_service already registered by ~p~n", [OldPid])
end.
server_loop() ->
receive
{From, hello} ->
io:format("Server (~p) received 'hello' from ~p~n", [self(), From]),
From ! {self(), "Hi from server!"},
server_loop();
_ ->
io:format("Server (~p) received unknown message~n", [self()]),
server_loop()
end.
% Client Functions
client_task() ->
io:format("Client (~p) trying to find my_global_service...~n", [self()]),
case global:whereis_name(my_global_service) of
undefined ->
io:format("Client: my_global_service not found!~n");
ServerPid ->
io:format("Client: Found server ~p, sending 'hello'...~n", [ServerPid]),
ServerPid ! {self(), hello},
receive
{ServerPid, Response} ->
io:format("Client: Received response from server: '~s'~n", [Response])
after 5000 ->
io:format("Client: No response from server within 5 seconds.~n")
end
end.
% Main entry point
main() ->
% Start the server process
spawn(?MODULE, server_init, []),
timer:sleep(100), % Give server time to register
% Start the client process
spawn(?MODULE, client_task, []),
timer:sleep(2000). % Allow processes to run and communicateRemoving Global Names
When a globally registered process terminates, the global module automatically unregisters its name. However, you can also explicitly unregister a name using global:unregister_name(Name).
This is useful if you want to replace a service, or if a process needs to temporarily relinquish its global name. Remember, once unregistered, other processes can no longer find it by that name.
Handling Name Collisions
What happens if two different processes (even on different nodes) try to register the same global name?
The global module ensures that a global name is unique across the entire distributed system. The first process to successfully register the name wins. Subsequent attempts to register the same name will fail and return {false, OldPid}, indicating who already holds the name.
This prevents ambiguity and ensures that whereis_name/1 always returns a single, correct PID.
Practical Applications
Global process registration is ideal for implementing:
- Singleton Services: A single instance of a service (e.g., a configuration manager, a logger) accessible from anywhere.
- Resource Managers: A process responsible for managing a shared resource that multiple parts of your distributed system need to access.
- Entry Points: Providing a well-known name for the main entry point of a distributed application.
It simplifies process discovery in complex distributed architectures.
How Global Registration Works
The global module achieves its magic by maintaining a consistent view of registered names across all connected Erlang nodes.
When a name is registered, this information is broadcast to all other nodes. When a node connects or disconnects, the global module updates its internal state to reflect the current cluster topology and available global names.
This ensures that global:whereis_name/1 can quickly find the correct PID, no matter where it resides.
Global Registration Check
Consider a distributed Erlang system with two nodes, nodeA and nodeB, both connected. A process on nodeA successfully registers itself with global:register_name(my_service, self()).
What will happen if a process on nodeB then tries to call global:register_name(my_service, self())?
Global Names: A Distributed Directory
In this lesson, you learned about global process registration using Erlang's global module:
- It provides a way to assign unique names to processes that are discoverable across an entire distributed Erlang cluster.
global:register_name(Name, Pid)makes a process globally accessible.global:whereis_name(Name)allows any process on any connected node to find the PID associated with a global name.- The
globalmodule handles name uniqueness and automatically unregisters processes when they terminate, simplifying distributed process management.
Global names are fundamental for building robust, fault-tolerant, and discoverable services in distributed Erlang applications.
常见问题解答
「全局进程注册」课时是免费的吗?
是的 — 「全局进程注册」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Erlang OTP: Distributed & Fault-Tolerant Systems Programming 课程的其余内容,请升级到 CoddyKit PRO。 Erlang OTP: Distributed & Fault-Tolerant Systems Programming 课程共包含 4 节课。
「全局进程注册」这节课中我会学到什么?
管理全局进程名称,并在分布式 Erlang 集群中发现进程,以协调各项操作。 你通过在浏览器中直接运行的动手代码来练习 Erlang OTP: Distributed & Fault-Tolerant Systems Programming,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Erlang OTP: Distributed & Fault-Tolerant Systems Programming 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Erlang OTP: Distributed & Fault-Tolerant Systems Programming 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。
「全局进程注册」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Erlang OTP: Distributed & Fault-Tolerant Systems Programming 课中编写并运行代码吗?
能。每节 Erlang OTP: Distributed & Fault-Tolerant Systems Programming 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。