如何在 Erlang 中编写一个简单的接收循环
假设我在 Erlang 中有 2 个进程,每个进程都有一个运行的接收循环。 我想从 ProcessB 向 ProcessA 发送信号,但 ProcessA 实际上不需要对其执行任何操作。 ProcessA只需要知道ProcessB发送了消息。
以下是我目前的实现方式:
receive
{message_from_process_b} ->
io:format("received a message from b", []);
end,
%% at this point I know that I've received the message from B.
效果很好。 但出于好奇,如果没有 io:format 行,我该如何编写呢? (我需要进程 A 阻塞,直到收到来自 B 的消息,这是更大的 Yaws / Yapp 的一部分,服务器需要响应才能显示页面。)
Let's suppose that I have 2 processes in Erlang, and each process has a receive loop running. I want to send a signal from ProcessB to ProcessA but ProcessA doesn't actually need to do anything with it. ProcessA only needs to know that ProcessB sent the message.
Here's how I have it implemented currently:
receive
{message_from_process_b} ->
io:format("received a message from b", []);
end,
%% at this point I know that I've received the message from B.
It works fine. But out of curiosity, how can I write this without the io:format
line? (I need Process A to block until receiving the message from B, this is part of a larger Yaws / Yapp and the server needs a response before it can show the page.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您确实应该构建一个 OTP 应用程序,并且进程 B 应该是 gen_server。
消息发送语义和构建您自己的发送/接收协议都非常好,但除非您真正知道自己在做什么,否则您将开始构建难以维护的服务器。
我的建议是坐下来研究如何使您的应用程序成为一个结构正确的标准 OTP 应用程序,以便您将 Yaws 作为应用程序树的一部分启动,并在正常的 OTP 框架内使用 ProcessA 和 ProcessB 执行所有其他操作。
You really should be building an OTP application and Process B should be a gen_server.
The message sending semantics and building your own send/receive protocols are all very fine but unless you really know what you are doing you will start building unmaintainable servers.
My advice would be sit down and work out how to make your application a properly structured standard OTP application so that you start Yaws as part of an application tree and do all the other stuff with ProcessA and ProcessB inside the normal OTP framework.
你可以用像 nop 这样的原子替换 io:format
you could replace the io:format with an atom like nop
正如 Simeon Pilgrim 所说,你可以这样做,
但你可能想添加一个超时:
以满足从未收到消息的情况(即传感器中发生的故障)。
As Simeon Pilgrim said, you can do
But you might want to add a timeout:
to cater for never receiving the message (i.e. a fault occurring in the sensder).