In Erlang is there any way that a message sender can wait on a response, so it only continues execution once the message has been processed?
And I mean something like this:
Actor ! DoSomething
Continue to this next line of code when DoSomething has been processed
I know a callback can be made by sending the Pid of the sender, but is there any other way to wait?
First thing to understand is that Erlang was built to deal with asynchronous message passing. As such, the only way to have synchronous message passing is to implement something akin to an acknowledgement.
Imagine two processes, P1 and P2. P1 might run the following code:
P2, on its side might just run the following:
So then you might spawn p2 as a new process. This one will sit waiting for any message. When you then call p1, it sends a message to P2, which then processes it (
io:format/2) and replies to P1. Because P1 was waiting for a reply, no additional code was run inside that process.That’s the basic and only way to implement blocking calls. The suggestions to use
gen_server:callroughly implement what I’ve just shown. It’s hidden from the programmer, though.