Erlang 并发模型
这可能是一个非常基本的问题,但是 Erlang 是否能够在另一个进程上调用方法并等待它以某种对象类型进行响应,而无需休眠线程?
This could be a very basic question but is Erlang capable of calling a method on another prcoess and wait for it to repond back with some object type without sleeping threads?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
好吧,如果您等待答案,调用进程最终将不得不休眠……但这没什么大不了的。
当进程卡在接收循环中时,其他进程可以工作。事实上,有数千个进程在等待消息的情况并不罕见。而且由于 Erlang 进程不是真正的操作系统线程,因此它们非常轻量级,因此性能损失很小。
事实上,睡眠的实现方式如下:
Well, if you're waiting for an answer, the calling process will have to sleep eventually… But that's no big deal.
While processes are stuck on the
receive
loop, other processes can work. In fact, it's not uncommon to have thousands of processes just waiting for messages. And since Erlang processes are not true OS threads, they're very lightweight so the performance loss is minimal.In fact, the way sleep is implemented looks like:
是的,如果您是这个意思,可以查看邮箱。假设我们已经向另一个进程发送了一条消息,现在我们想查看另一个进程是否已向我们发送了一些内容。但我们不想阻止接收:
将尝试与邮箱中的
Pattern
和Pattern2
进行匹配。如果没有匹配,它将立即超时并转到AfterBody
。这允许您对邮箱实施非阻塞查看。如果进程是
gen_server
,则当回调返回到gen_server
时,可以通过处理内部状态和Timeout
设置来实现相同的效果的控制。您可以将超时设置为0
来实现此目的。Yes, it is possible to peek into the mailbox if that is what you mean. Say we have sent a message to another process and now we want to see if the other process has sent something back to us. But we don't want to block on the receive:
will try to match against the
Pattern
andPattern2
in the mailbox. If none matches, it will immediately time out and go toAfterBody
. This allows you to implement a non-blocking peek into the mailbox.If the process is a
gen_server
the same thing can be had by playing with the internal state and theTimeout
setting when a callback returns to thegen_server
's control. You can set a Timeout of0
to achieve this.从这个问题中我们得到的是,我们正在谈论
同步消息传递
。是的 ! Erlang 可以完美地做到这一点,这是 Erlang 中处理并发的最基本方法。请考虑以下情况:上面的代码显示,一个进程向另一个进程发送消息,并立即进入等待状态(等待回复),而不必休眠。如果5秒内没有得到回复,就会退出。
What am getting from the question is that we are talking of
Synchronous Message Passing
. YES ! Erlang can do this perfectly well, its the most basic way of handling concurrency in Erlang. Consider this below:The code above shows that a processes sends a message to another and immediately goes into waiting (for a reply) without having to sleep. If it does not get a reply within 5 seconds, it will exit.