Does Erlang support the "ask" operation?

In Akka, you have two different sending mechanisms: !in order to tell the actor’s material, and ?in order to ask the actor about things, the main difference for strangers is that they actor ! messageare fire and forget and actor ? messagereturns the promise of the result, which is then returned to later time should be allowed.

I could not find anything about this in Erlang, because the search engine "Erlang ask operation" or just "Erlang ask" gives less useful results.

+4
source share
3 answers

No, this is not so, but what you ask for is easy to implement:

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

Waiting for the result of the promise, you can now do:

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 do not want to do anything between request and force, you can use the OTP behavior gen_server, which has it gen_server:call/3, basically implementing these two functions at a time.

Please note that in the above example, we request a monitor link to the target Pid, which allows us to track it if it dies. We also use this link as a unique tag for a promise, so that we can find it among other messages that look like in a mailbox.

+10
source

Erlang promises . . . . , Erlang promises .

+1

? Akka !. : , sender !. , . .

( , , - ).

ask , !.

You can implement the same template in Erlang.

0
source

Source: https://habr.com/ru/post/1629467/


All Articles