构建并发系统:GenServer与多任务管理
1. GenServer使用与原理
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 来停止服务器进程,此调用会向服务器发出同步请求。
GenServer进程的生命周期如下:
graph LR
classDef startend fill:#F5EBFF,stroke:#BE8FED,stroke-width:2px
classDef process fill:#E5F6FF,strok
超级会员免费看
订阅专栏 解锁全文
36

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



