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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With