[erlang-questions] Order of message processing by a gen_server

Lev Walkin vlm@REDACTED
Wed Dec 5 07:41:45 CET 2007


Jack Orenstein wrote:
> On Dec 5, 2007, at 12:40 AM, Lev Walkin wrote:
> 
>> Jack Orenstein wrote:
>>> Suppose I have a gen_server process whose queue contains {a} and 
>>> {b}.  Does the order of the handle_call function clauses determine 
>>> which  message is processed first? I.e., if the function clauses are
>>>      handle_call({a}, From, State) -> ...
>>>      handle_call({b}, From, State) -> ...
>>> is it guaranteed that {a} will be processed first?
>>
>> Yes, but this is implementation detail and is not guaranteed
>> by the standard.
> 
> What I am trying to do is to write a server that will process a series 
> of requests, always the same requests (phase1, phase2, phase3) in the 
> same order. But I want to be able to cancel the sequence of requests at 
> any point, resetting the process state to be ready for phase1 again. If 
> I write my own function with a receive, I can do this:
> 
>          loop(State) ->
>              receive
>                  cancel -> ...
>                  phase1 -> ...
>                  phase2 -> ...
>                  phase3 -> ...
>              end.
> 
> Normally this server will receive messages phase1, phase2, phase3 in 
> order. But if a cancel message shows up, e.g. after phase2, it takes 
> priority (if I understand receive correctly).
> 
> I'd like to use a gen_server, but it sounds like I can't do anything 
> that is guaranteed by the language (not the implementation) to handle 
> the cancel message with higher priority than any of the other messages. 
> I.e.,
> 
>         handle_call({cancel}, From, State) -> ...
>         handle_call({phase1}, From, State) -> ...
>         handle_call({phase2}, From, State) -> ...
>         handle_call({phase3}, From, State) -> ...
> 
> isn't guaranteed to work similarly to the loop function above.
> 
> Any advice on how to proceed?

I was under impression that even your original approach (with barebones
receive) is not formally guaranteed to work the way you described.

However, out of practicality I'd advise you to rely on handle_call
being similar to receive in its ability to receive out-of-bound
messages. Don't worry about it unless you're writing Space Shuttle
Mission Critical System with 20-years expected code lifetime.

-- 
Lev Walkin
vlm@REDACTED



More information about the erlang-questions mailing list