[erlang-questions] questions about gen_server behaviour

Ladislav Lenart lenartlad@REDACTED
Fri May 25 15:24:02 CEST 2007


Ming Zhao(Jimmy) wrote:
> Could anyone explain these two functions below in details (better with 
> example)?
> 1.synchronous request ----call
> Makes a synchronous call to the gen_server ||by sending a request and 
> waiting until a reply arrives or a timout occurs.
> who sends the reply? what exactly is the reply?
Suppose you have two processes A and B. Both are gen_servers.
If A wants something from B, it does:
   ...
   {ok, Result} = gen_server:call(B, something),
   ...
This blocks A until a reply from B arrives or a timeout occurs
(which is 5 seconds by default I think).

If B implements the following in its gen_server callback module:
   ...
   handle_call(something, _From, _State) ->
     {reply, {ok, anything}, State};
   ...
A will receive atom {ok, anything}. Otherwise A will (eventually)
crash with timeout.

> 2.asynchronous request ----cast
> Sends an asynchronous request to the gen_server ||and returns |ok| 
> immediately
> who sends the ok?
No one. Atom ok is returned by the cast function itself (it is
its last expression).

> these 2 functions seems to me the same ,
> so confused by them ..
But they are not.

gen_server:cast(Pid, message) is a "gen_server way" for Pid ! message.
But gen_server:call is used to retrieve some information from another
process. It is implemented as two casts: one from the requestor process
to the provider process and one back. The gen_server:call machinery
ensures that process A (from the example above) will wake up *only*
when it receives reply to its request.

Hope this helps,

Ladislav Lenart




More information about the erlang-questions mailing list