why doesn't this erlang code work?
fib(N)->
P1 = spawn(fun concFib:conFib/0),
开发者_高级运维 P2 = spawn(fun concFib:conFib/0),
X=rpc(P1,N-2),Y=rpc(P2,N-1),X+Y.
conFib()->
receive
{Client,N} -> Client ! regfib(N)
end.
rpc(Pid,Request)->
case erlang:is_process_alive(Pid) of
true -> begin
Pid ! {self(),Request},
receive
{Pid,Respond} -> Respond
end
end;
false -> io:format("~w process is dead.",[Pid])
end.
regfib(N)->
case N<2 of
true -> 1;
false -> regfib(N,1,1,1)
end.
regfib(N,N,X,_)-> X ;
regfib(N,M,X,Y)-> regfib(N,M+1,X+Y,X).
The idea is to divide the fib(N) process into two process one calculates fib(N-2) and the other one calc. fib(N-1) concurrently as fib(N)=fib(N-1)+fib(N-2). when i run the previous code nothing happen and the cursor stop as in finite loop or waiting for not arriving result.
plzzz i need help i'm a new Erlang programmer,thanks in advance :)In your conFib you send an integer, but await a tuple in rpc. Should change it to:
conFib()->
receive
{Client,N} -> Client ! {self(), regfib(N)}
end.
You can evade such situations by using timeout with after
in your receives.
To make the computation parallel you could do something like:
fib(N)->
P1 = spawn(fun test:conFib/0),
P2 = spawn(fun test:conFib/0),
P1 ! {self(), N - 2},
P2 ! {self(), N - 1},
receive
{_, R1} -> R1
end,
receive
{_, R2} -> R2
end,
R1 + R2.
The important part is that you send both of the requests before waiting for the answers. The part waiting for the answers could of course be done in a more beautiful way.
精彩评论