I was working though a problem and noticed some code where a previous programmer was passing messages using the standard convention of PID ! Message. I have been using gen_server:cast/2. I was wondering if somebody could explain to me the critical differences and considerations when choosing between the two?
相关问题
- Load script async?
- C# An asynchronous operation cannot be started at
- aio_write on linux with rtkaio is sometimes long
- await work in chrome console without async wrapper
- Is “new” in Erlang part of the official standard a
相关文章
- With a Promise, why do browsers return a reject tw
- Asynchronous SHA256 Hashing
- Does aiohttp have ORM?
- How do I modify a record in erlang?
- Check active timers in Erlang
- Can each Iteration of a for loop/for_each be done
- How does robospice manage activity lifecycle?
- How to call a async function from a synchronized c
In addition to legoscia post I would say that it is easier to trace dedicated function API than messages. Especially in prod environment.
There are a few minor differences:
handle_cast
and "normal" messages inhandle_info
.ok
. Sending a message with!
fails withbadarg
if you are sending a message to an atom that is currently not registered by a process. (Sending a message to a pid never causes an error, even if the process is dead.)gen_server:cast
will spawn a background process to establish the connection and send the message, and return immediately, while!
only returns once the connection is established. (See the code forgen_server:do_send
.)As for when to choose one or the other, it's mostly a matter of taste. I'd say that if the message could be thought of as an asynchronous API function for the gen_server, then it should use cast, and have a specific API function in the gen_server callback module. That is, instead of calling
gen_server:cast
directly, like this:make a function call:
and implement that function like the direct cast above. That encapsulates the specific protocol of the gen_server inside its own module.
In my mind, "plain" messages would be used for events, as opposed to API calls. An example would be monitor messages,
{'DOWN', Ref, process, Id, Reason}
, and events of a similar kind that might happen in your system.