在Erlang中,如何从派生的进程中获取返回值?

vptzau2j  于 2022-12-16  发布在  Erlang
关注(0)|答案(2)|浏览(200)

下面的代码:

-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中的list [1,2],但是,由于使用了spawn,返回的是进程的pid而不是函数的list,所以我得到了以下输出:

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]

我怎样才能做到这一点?

ffscu2ro

ffscu2ro1#

要在进程之间传递信息,可以使用!向另一个进程的邮箱发送消息,然后使用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时存在一些风险:如果一个工作进程在发送消息到你的主进程之前崩溃了,那么你的主进程在等待来自崩溃进程的消息时将无限期地停留在接收状态。2一个解决方案是:在接收中使用超时。另一个:使用spawn_monitor()函数。

wfsdck30

wfsdck302#

您需要为此使用消息(或信号),因为代码在单独的进程中运行。
在这种情况下,我喜欢使用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].

相关问题