Search code examples
erlangerlang-otp

Can a function be called in a gen_server process by its Pid


If I have a group of gen servers called lock, can I call a function say

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

from the Pid of individual processes of that gen_server instead of generic lock:hello().

I tried Pid=<0.91.0> (so the Pid is return when i start a chld in my supervisor), and Pid:hello(). gives a bad argument is it impossible to do this??

Is it a better idea to send a message instead to call that function??


Solution

  • You can call 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]).
    

    ...

    hello() ->
      gen_server:call(Pid, hello).
    
    
    handle_call(hello, _From, _State) ->
        Reply = io:format("Hello, world!~n")
        {reply, Reply, State}.
    

    There is no Pid:Function API in Erlang.

    In both cases calling gen server will serialize the call, providing you are using gen_server API. But going with function call you can choose synchronous reply.

    If the hello is just placed in gen_server module (without gen_server:call) it will be executed in context of calling process, not gen_server one's.