[erlang-questions] gen_server & wait/notify

Vlad Dumitrescu vladdu55@REDACTED
Fri Sep 29 09:30:38 CEST 2017


Hi!

If you want your gen_server to be able to service other requests during the
async request, then you want something like below (modulo error handling
and typos and bugs)

best regards,
Vlad

handle_call({request, Data#data{uid=UID}}, From, State) ->
    make_async_req(Data),
    NewState = State#state{pending=[{UID, From}|State#state.pending]}
    {noreply, NewState}.

handle_info({response, Response#response{uid=UID}},
State=#state{pending=Pending}) ->
    {value, {UID, From}, NewPending} = lists:keytake(UID, 1, Pending),
    gen_server:reply(From, Response),
    NewState = State#state{pending=NewPending},
    {noreply, NewState}.


On Fri, Sep 29, 2017 at 2:58 AM, Chris Waymire <chris@REDACTED> wrote:

> I need some help finding a pattern/solution to a problem that is proving
> more difficult then it should, it seems.
>
> I have a gen_server module that needs to take an asynchronous
> request/response operation and expose it as a synchronous operation.
> Typically I would use receive to block and have the asynchronous operation
> issue a message to unblock it but that won't work (i believe) with a
> gen_server since it loops over receive and forwards them to calls to
> handle_info. The code below demonstrates the core of the matter of what i'm
> talking about. I'm not sure what the solution would be to achieve this
> functionality while using the gen_server behaviour.
>
>
>
> handle_call({request, Data#data{uid=UID}}, _From, State) ->
>     make_asycnc_req(Data),
>     receive
>         {UID, Response} -> {reply, Response, State}
>     end.
>
> handle_info({response, Response#response{uid=UID}}, State) ->
>     self() ! {UID, Response},
>     {noreply, State}.
>
> Thanks,
>
> -- Chris
>
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20170929/9a85088e/attachment.htm>


More information about the erlang-questions mailing list