【问题标题】:How can I get return value from a spawned process in Erlang?如何从 Erlang 的衍生进程中获取返回值?
【发布时间】:2021-02-24 11:14:42
【问题描述】:

我有以下代码:

-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 而不是函数中的列表,所以我得到以下输出:

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]

我怎样才能做到这一点?

【问题讨论】:

    标签: process erlang distributed-computing spawn erlang-otp


    【解决方案1】:

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

    在外壳中:

    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()。

    【讨论】:

      【解决方案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].
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-18
        • 2015-12-05
        • 1970-01-01
        • 2010-12-07
        • 2018-09-09
        • 2013-04-13
        相关资源
        最近更新 更多