0

我是 Erlang 的新手,我需要生成两个运行 add 函数的进程,然后添加两个数字。进程一和进程二的分配值显示进程ID,我需要捕获该值。

如何在我的calc函数中读取 add(N) 函数的返回值?

-module(myerl).
-export([calc/1,add/1]).

add(N) ->
    N + 5.


calc(L)

pone = spawn( fun() -> add(A) end),   
ptwo = spawn( fun() -> add(B) end),

Result = Pone + Ptwo,
io:format("result ~p~n", [Result]). 
4

2 回答 2

3

您需要使用消息传递。您必须将消息连同结果一起发送回调用进程。该spawn函数向新生成的进程返回一个 PID(进程标识符),而不是其执行的结果。

这个例子应该做你所期望的:

calc(A, B) ->
    Self = self(),       % The spawned funs need a Pid to send to, use a closure
    POne = spawn(fun() -> Self ! {self(), add(A)} end),
    PTwo = spawn(fun() -> Self ! {self(), add(B)} end),
    wait_for_response(POne, PTwo, 0).

wait_for_response(undefined, undefined, Sum) ->
    Sum;
wait_for_response(POne, PTwo, Sum) ->
    receive
        {POne, V} -> wait_for_response(undefined, PTwo, Sum + V);
        {PTwo, V} -> wait_for_response(POne, undefined, Sum + V)
    end.
于 2013-01-23T20:42:43.547 回答
2

@Soup d'Campbells 的解释很好。我本能地做了一些稍微不同的事情,以一种玩具的方式,预测了子进程的一些不良行为。另外,我允许输入是数字列表,而不仅仅是 2。

-module(myerl).
-export([calc/1, add/1]).

calc(NumList) when is_list(NumList)->
    Parent = self(),
    _Pids = [spawn(fun()-> Parent ! add(ANum) end) || ANum <- NumList],
    collect(length(NumList), 0);
calc(_) -> 
    {error, badarg}.

collect(0, Sum)   -> 
    Sum;
collect(Cnt, Sum) ->
    receive
        N when is_number(N) -> 
            collect(Cnt-1, Sum + N);
        _Bad ->  % returned something that isnt a number
            collect(Cnt-1, Sum)
    after 1000 -> % died or is too slow
        collect(Cnt-1, Sum)
    end.

add(N) -> 
    N + 5.
于 2013-01-23T21:17:01.963 回答