二郎神:使用gen_server区别:施放/ 2和标准的消息传递 [英] Erlang: difference between using gen_server:cast/2 and standard message passing

查看:270
本文介绍了二郎神:使用gen_server区别:施放/ 2和标准的消息传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的工作虽然问题并注意到一些code其中一个previous程序员使用PID的标准约定传递消息!信息。我一直在使用gen_server:铸铁/ 2。我在想,如果有人可以给我两之间进行选择时解释关键的差异和考虑?

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?

推荐答案

有一些细微差别:


  • 显然,gen_server处理铸件在 handle_cast handle_info 正常的消息。

  • 系统投从来没有失败;它总是返回确定。发送一条消息,失败 badarg 如果您要发送消息到目前没有被注册的原子处理。 (发送消息到PID不会导致错误,即使过程已经死了。)

  • 如果在gen_server是当前未连接到本地节点的远程节点上运行,则 gen_server:铸造将产生一个后台进程,以建立连接并发送该消息,并立即返回,而!一旦连接建立只返回。 (见code为 gen_server:do_send

  • Obviously, the gen_server handles casts in handle_cast and "normal" messages in handle_info.
  • A cast never fails; it always returns ok. Sending a message with ! fails with badarg 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.)
  • If the gen_server is running on a remote node that is not currently connected to the local node, then 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 for gen_server:do_send.)

至于什么时候选择一个或另一个,它主要是一个品味的问题。我会说,如果该消息可以被认为是作为gen_server异步API函数,那么它应该使用铸铁,的有gen_server回调模块在一个特定的API函数。也就是说,不是打电话, gen_server:铸造直接,就像这样:

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:

gen_server:cast(foo_proc, {some_message, 42})

做一个函数调用:

make a function call:

foo_proc:some_message(42)

和实施类似上面的直接投该功能。它封装了自己的模块内部的gen_server的具体协议。

and implement that function like the direct cast above. That encapsulates the specific protocol of the gen_server inside its own module.

在我的脑海里,普通的消息将被用于事件,而不是API调用。一个例子是监控的消息, {'DOWN',参考文献,流程,编号,原因} 和事件类似的一种在你的系统可能发生的。

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.

这篇关于二郎神:使用gen_server区别:施放/ 2和标准的消息传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆