Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Erlang support an "ask" operation?

In Akka you got two different sending mechanisms: ! for telling the actor stuff, and ? for asking an actor about stuff, the main difference for those unfamiliar is that actor ! message is a fire-and-forget operation, and actor ? message returns a promise of a result that then at a later time needs to be resolved.

I haven't been able to find anything regarding this in Erlang as googling "Erlang ask operation" or simply "Erlang ask" yields less-than helpful results.

like image 351
Electric Coffee Avatar asked Dec 15 '22 08:12

Electric Coffee


1 Answers

No, it does not, but what you request is easy to implement:

ask(Pid, M) ->
  Promise = erlang:monitor(process, Pid),
  Pid ! {ask, Promise, M},
  Promise.

Awaiting the result of the promise can now be done by:

force(Promise, Timeout) ->
  receive
    {result, Promise, R} ->
      erlang:demonitor(Promise, [flush]),
      {ok, R};
    {'DOWN', Promise, process, _, Reason} ->
      {error, {callee_died, Reason}}
  after Timeout -> {error, timeout}
  end.

If you don't want to do anything in between asking and the force, then you can use the OTP behavior gen_server which has a gen_server:call/3 essentially implementing these two functions in one go.

Note how in the above we request a monitor reference on the target Pid which allows us to monitor it if it dies. We also use this reference as a unique tag for the promise so we can find it among other messages that looks like it in the mailbox.

like image 56
I GIVE CRAP ANSWERS Avatar answered Dec 24 '22 09:12

I GIVE CRAP ANSWERS