【问题标题】:Erlang: Child process execute normally until received "die"?Erlang:子进程正常执行直到收到“死”?
【发布时间】:2015-01-13 14:59:38
【问题描述】:

我想知道是否可以让子进程继续正常运行,直到它收到来自父进程的“死亡”消息。

这是子进程的代码。

-module(sensor).
-export([start/1]).     % must also export function that will be spawned


%%  create second thread, pass self() as argument so it knows how to reply
%%  exchange messages with second thread until sum=0
start(SlaveNr) ->
    %this part is not right. It waits for die and does nothing else
    receive
        die ->
            io:format("slave ~p: received die~n", [SlaveNr])
    end,
    random:seed(now()),
    Measurement = random:uniform(11),
    if Measurement == 11 ->
        exit(crash);
    true->
        io:fwrite("slave ~p Random # ~p~n",[SlaveNr, Measurement])
    end,
    Sleep_time = random:uniform(10000),
    timer:sleep(Sleep_time),
    start(SlaveNr).

如您所见,它没有正常执行。它只是等到它收到一个 die 消息。那么我怎样才能让它执行它的正常功能,直到它收到来自父进程的 die 指示所有子进程都应该退出?

【问题讨论】:

    标签: concurrency erlang


    【解决方案1】:

    我了解您想在每个循环中检查邮箱,您可以通过添加 0 ms 的 timout 来实现。所以进程会检查是否有任何收到的消息匹配死掉,如果不匹配则立即继续。

    receive
            die ->
                io:format("slave ~p: received die~n", [SlaveNr])
            after 0 ->
                ok
        end,
    

    始终可以使用exit/2 函数停止进程:exit(Pid,Reason)。在这种情况下,您不必在传感器模块中添加任何代码。如果您将原子normal 用作Reason,则该进程将完全像自己正常死亡一样死亡。

    【讨论】:

    • 这是完美的。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-08
    • 2014-08-18
    • 2012-02-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多