views:

243

answers:

2
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 :)

+5  A: 

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.

Zed
Thanks Zed :),It solved the problem,but the logic of code doesn't work as i expected :(.X=rpc(P1,N-2) and X=rpc(P2,N-1) don't work concurrently the second one wait for the first to be done.i want to calculate fib(N-1) and fib(N-2) at the same time each one in distinct process.I wana more help plz...
Fuzzix
+4  A: 

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.

Rickard
thanks Rickard :)...I got it..forgive me ur answer is more specific to me put the as Q was as Zed answered first.
Fuzzix