如何在 Erlang 中编写一个简单的接收循环

发布于 2024-07-27 01:56:21 字数 469 浏览 4 评论 0原文

假设我在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

青衫负雪 2024-08-03 01:56:21

您确实应该构建一个 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.

活泼老夫 2024-08-03 01:56:21

你可以用像 nop 这样的原子替换 io:format

you could replace the io:format with an atom like nop

镜花水月 2024-08-03 01:56:21

正如 Simeon Pilgrim 所说,你可以这样做,

receive   
    {message_from_process_b} -> ok
end,  

但你可能想添加一个超时:

receive   
    {message_from_process_b} -> ok
    after 1000 -> io:format("timeout!", [])
end,

以满足从未收到消息的情况(即传感器中发生的故障)。

As Simeon Pilgrim said, you can do

receive   
    {message_from_process_b} -> ok
end,  

But you might want to add a timeout:

receive   
    {message_from_process_b} -> ok
    after 1000 -> io:format("timeout!", [])
end,

to cater for never receiving the message (i.e. a fault occurring in the sensder).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文