可以通过Pid在gen_server进程中调用函数

hom*_*jay 1 erlang erlang-otp

如果我有一组名为lock的gen服务器,我可以调用一个函数说

hello() -> io:format("Hello, world!~n").

来自gen_server的各个进程的Pid而不是泛型 lock:hello().

我试过了Pid=<0.91.0>(所以当我在我的主管中开始一个chid时,Pid会返回)和Pid:hello().给出一个不好的论点是不可能这样做的?

发送消息而不是调用该函数更好吗?

use*_*720 5

你可以调用gen_server:call(Pid,TuplePatternThatMatchesOnCallback)

-behaviour(gen_server).

%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
         terminate/2, code_change/3]).
Run Code Online (Sandbox Code Playgroud)

...

hello() ->
  gen_server:call(Pid, hello).


handle_call(hello, _From, _State) ->
    Reply = io:format("Hello, world!~n")
    {reply, Reply, State}.
Run Code Online (Sandbox Code Playgroud)

Erlang中没有Pid:Function API.

在这两种情况下,调用gen服务器将序列化调用,前提是您正在使用gen_server API.但是使用函数调用可以选择同步回复.

如果hello刚刚放在gen_server模块中(没有gen_server:call),它将在调用进程的上下文中执行,而不是gen_server one.