Concurrency Erlang:子进程正常执行,直到收到";死;?

Concurrency Erlang:子进程正常执行,直到收到";死;?,concurrency,erlang,Concurrency,Erlang,我想知道是否有可能让子进程继续正常运行,直到它从父进程收到“die”消息 下面是子进程的代码 -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 th

我想知道是否有可能让子进程继续正常运行,直到它从父进程收到“die”消息

下面是子进程的代码

-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?我知道您希望在每个循环中检查邮箱,您可以通过添加0毫秒的timout来实现这一点。因此,进程将检查收到的消息是否与die匹配,如果没有,它将立即继续

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

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

这是完美的。非常感谢。