深入探索 Elixir 并发系统:GenServer 与多任务管理
1. GenServer 的使用与特性
GenServer 是实现通用服务器进程的行为。当处理错误时,若无法继续执行,应返回 {:stop, reason} ;若停止服务器是正常操作流程,则使用 :ignore 。从 handle_* 回调中返回 {:stop, reason, new_state} 会使 GenServer 停止服务器进程。若终止是标准工作流程的一部分,应使用原子 :normal 作为停止原因。若在 handle_call/3 中,还需在终止前响应调用者,则可返回 {:stop, reason, response, new_state} 。
即使要终止进程,也需返回新状态,因为在终止前,GenServer 会调用 terminate/2 回调函数,将终止原因和进程的最终状态传递给它,这在需要执行清理操作时很有用。此外,还可从客户端进程调用 GenServer.stop/3 来停止服务器进程,此调用会向服务器发出同步请求。
2. GenServer 进程的生命周期
GenServer 进程的生命周期可通过以下流程图展示:
graph LR
classDef startend fill:#F5EBFF,stroke:#B
超级会员免费看
订阅专栏 解锁全文
38

被折叠的 条评论
为什么被折叠?



