I'm looking for good examples of Erlang asynchronous message handling with gen_server:cast/2.
I've seen an example in the OTP ssh module, which receives a request through Module:handle_cast/2, holding it in a local queue of the module, and sending back a reply message corresponding to the request later, by explicitly sending a message to the caller. When I tried to read it, I could barely keep track of the code, and wasn't able to grasp the idea.
A piece of pseudo code is appreciated.
I believe you're referring to the ssh_connection_manager module.
When you perform a gen_server:cast/2
, the request is handled in the Module:handle_cast/2
function. A couple of things to notice here:
handle_cast
parameters you don't have information about the sender, so you cannot - unless you send this information within the message itself - send back some result to it.gen_server:cast/2
, won't wait for a reply. Actually, it doesn't even care if the message arrived or not (with some exceptions).handle_cast/2
, you can just return a noreply or a stop tuple, so no way to return a reply there.Said that, the idea behind the code you've been looking at should be (simplifying things):
gen_server:call/2
is madeAt this point you have to two possibilities, depending if you need more information to compute your result from other clients (A) or from the same client (B):
gen_server:call/2
.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