Reputation: 35
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??
Upvotes: 1
Views: 1238
Reputation: 815
When you call a function in a gen_server module, the function is not executed in the gen_server process. It is executed in the caller process.
If you want the gen_server process to do something, you should use the gen_server:call or the gen_server:cast functions:
For example, the gen_server:call/2 function will take a pid and a message that will be sent along with the call. The gen_server will then run it's handle_call function in the gen_server process.
Normally, you would have functions in the same module that defines the gen_server that will do the gen_server:call so that the caller will not have to care. That creates a clean API for others and hides the gen_server specific stuff.
It may be a little bit tricky to get all the pieces together but it's simple once you have. Check out this chapter of LYSE: http://learnyousomeerlang.com/clients-and-servers
Upvotes: 4
Reputation: 3598
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.
Upvotes: 5
Reputation: 8340
You can call the function hello
from anywhere you want. If you call it 1000 times from 1000 processes, each process will be executing the function in parallel not interfering with each other. You just call it like that lock:hello().
from each one of those processes, so you call a specific function hello
that is defined in a specific module lock
and which takes zero arguments.
Probably there is something you didn't mention in your question?
Upvotes: 1