如何从 Erlang 中的派生进程中获取 return 值?

How can I get return value from a spawned process in Erlang?

我有以下代码:

-module(a).
-compile(export_all).

say(2,0) ->
    [1,2];

say(A,B) ->
    say(A-1,B-1).

loop(0) ->
    io:format("");

loop(Times) ->
    L = spawn(a, say, [4,2]),
    io:fwrite( "L is ~w  ~n", [L] ),
    loop(Times-1).

run() ->
    loop(4).

每次函数 'say' 完成时,我都希望在 L 中拥有列表 [1,2]。但是,由于使用了 spawn,返回的是进程的 pid 而不是函数 say 的列表,因此我得到以下输出:

L is <0.113.0>  
L is <0.114.0>  
L is <0.115.0>  
L is <0.116.0>  

我想要的是

L is [1,2]
L is [1,2]
L is [1,2]
L is [1,2]

我怎样才能做到这一点?

您需要为此使用消息(或信号),因为代码是 运行 在单独的进程中。

在那种情况下我喜欢使用 spawn_monitor:

1> {Pid, MonitorReference} = spawn_monitor(fun() -> timer:sleep(10000), exit({ok, [1,2]}) end),
1> receive {'DOWN', MonitorReference, process, Pid, {ok, Result}} -> Result end.

请记住,您可以同时 receive 接收多封邮件,或者您可以按顺序接收它们(将乱序的邮件留在邮箱中)。因此,您可以生成多个线程并等待所有线程完成,收集结果:

work(Workload) ->
    JobReference = make_ref(),
    PidReferences = [spawn_monitor(fun() -> exit({JobReference, do_stuff(WorkSlice)}) end) || WorkSlice <- Workload],
    [receive
        {'DOWN', Reference, process, Pid, {JobReference, Result}} -> Result;
        {'DOWN', Reference, process, Pid, Result} -> {error, Result}
    end || {Pid, Reference} <- PidReferences].

要在进程之间传递信息,您可以使用 ! 将消息发送到另一个进程的邮箱,并使用 receive clause 从进程邮箱中提取消息。这是一个例子:

-module(a).
-compile(export_all).

%% Worker process:
say(From, 2, 0) ->
    From ! {self(), [1,2]};
say(From, A, B) ->
    say(From, A-1, B-1).


%%  Main process:
loop(0) ->
    ok;
loop(Times) ->
    Pid = spawn(a, say, [self(), 4, 2]),
    receive  %%waits here for result before spawning another process--no concurrency
        {Pid, Result} ->
            io:fwrite( "L is ~w  ~n", [Result] )
    end,
    loop(Times-1).


%%  Test:
run() ->
    loop(4).

在shell:

7> c(a).   
a.erl:2: Warning: export_all flag enabled - all functions will be exported
{ok,a}

8> a:run().
L is [1,2]  
L is [1,2]  
L is [1,2]  
L is [1,2]  
ok

9> 

或者,您可以生成所有进程,然后读取结果:

-module(a).
-compile(export_all).

%% Worker process:
say(From, 2, 0) ->
    From ! [1,2];
say(From, A, B) ->
    say(From, A-1, B-1).


%%  Main process:
loop(N) ->
    loop(N, N).

loop(0, Times) ->
    display_results(Times);
loop(N, Times) ->
    spawn(a, say, [self(), 4, 2]),
    loop(N-1, Times).
 
display_results(0) -> 
    ok;
display_results(Times) ->
    receive
        Result ->
            io:format("L is ~w~n", [Result])
    end,
    display_results(Times-1).

%%  Test:
run() ->
    loop(4).

要确保您仅 receive 来自您生成的进程的消息,您可以这样做:

-module(a).
-compile(export_all).

%% Worker process:
say(From, 2, 0) ->
    From ! {self(), [1,2]};
say(From, A, B) ->
    say(From, A-1, B-1).


%%  Main process:
loop(Times) ->
    loop(Times, _Pids=[]).

loop(0, Pids) ->
    display_results(Pids);
loop(Times, Pids) ->
    Pid = spawn(a, say, [self(), 4, 2]),
    loop(Times-1, [Pid|Pids]).


display_results([]) -> 
    ok;
display_results([Pid|Pids]) ->
    receive
        {Pid, Result} ->
            io:format("L is ~w~n", [Result])
    end,
    display_results(Pids).

%%  Test:
run() ->
    loop(4).

像这样使用 receive 时存在一些风险:如果工作进程在将消息发送到您的主进程之前崩溃了,那么您的主进程将在等待消息时无限期地卡在接收中从崩溃的进程到达的消息。一种解决方案:在接收中使用超时。另:使用spawn_monitor().