问题描述
|
我有gen_server:
start(UserName) ->
case gen_server:start({global,UserName},player,[],[]) of
{ok,_} ->
io:format(\"Player: \" ++ UserName ++ \" started\");
{error,Error} ->
Error
end
...
现在我想编写函数来停止该发电服务器。我有:
stop(UserName) ->
gen_server:cast(UserName,stop).
handle_cast(stop,State) ->
{stop,normal,State};
handle_cast(_Msg,State) ->
{noreply,State}.
我运行它:
start(\"shk\").
Player: shk startedok
stop(shk).
ok
start(\"shk\").
{already_started,<0.268.0>}
但:
stop(player).
ok
是工作。
如何按名称运行gen_server并按名称停止?
谢谢。解决方法
首先:您必须始终使用相同的名称来命名进程,
\"foo\"
和foo
是不同的,因此首先要有严格的命名约定。
第二:使用全局注册的进程时,还需要使用ѭ6来寻址进程。
在我看来,您还应该将ѭ7convert函数转换为使用gen_server:call
,它将阻塞并让您从gen_server返回值。一个例子:
stop(Name) ->
gen_server:call({global,Name},stop).
handle_call(stop,_From,State) ->
{stop,normal,shutdown_ok,State}
这将向呼叫者返回“ 10”。
如此说来,global
模块相当有限,and12之类的替代方案提供了更好的分配。,我没有文档,但是我的猜测是您需要将用户名包装在gen_server类型的全局元组中。