process - 如何从 Erlang 中生成的进程获取返回值?

标签 process erlang distributed-computing spawn erlang-otp

我有以下代码:

-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]。然而,由于返回的是进程的 pid,而不是函数中的列表(比如由于使用 spawn),我得到以下输出:

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]

我怎样才能实现这个目标?

最佳答案

要在进程之间传递信息,可以使用 ! 将消息发送到另一个进程的邮箱,并使用 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(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).

在外壳中:

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).

为了确保您只接收来自您生成的进程的消息,您可以执行以下操作:

-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).

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

关于process - 如何从 Erlang 中生成的进程获取返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64804093/

相关文章:

c - 在 C 中等待兄弟进程

c - 如何观察父进程和子进程之间的资源争用

c++ - 统一2个空间内存

process - 代码设计流程?

python - 创建数组的 RDD

java - 领导者选举 LCR

ubuntu - 在旧 Ubuntu 10.04 上升级 couchdb/erlang

erlang - 从头开始实现 pmap。为什么我的执行速度很慢?

Erlang:有没有办法从我的模块中导出其他模块的导出?

tcp - 为什么 Hadoop 不使用 MPI 实现?