anell
Diverses solucions
control21.erl — 2.8 KB
Continguts del fitxer
-module(control2). -export([anell/1, proces/3, proces1/3, anell1/1, start/1, p/3]). anell(N) -> % Crear el node N io:format('Engego el procs: ~p. Envia missatges a 1~n',[N]), crearNode(N-1, self()), receive {fiCrearProces, Pid} -> io:format('Processos creats ~n') end, Pid!token, procesN(N,Pid, 3). crearNode(1, Pid) -> io:format('Engego el procs: 1. Envia missatges a 2~n'), Pid1 = spawn(?MODULE, proces, [1, Pid, 3]), PidC = self(), io:format('Procs ~p, ~p, ~p~n',[Pid1, PidC, Pid]), PidC!{fiCrearProces, Pid1}; crearNode(N, Pid) -> Pidi = spawn(?MODULE, proces, [N, Pid, 3]), io:format('Engego el procs: ~p. Envia missatges a ~p~n', [N,N+1]), crearNode(N-1, Pidi). proces(N,Pid,Comp) -> receive token when Comp /= 0 -> io:format('Procs: ~p , token n ~p~n', [N,Comp]), Pid!token, proces(N, Pid, Comp -1); token when Comp == 0 -> io:format('Finalitza procs ~p~n',[N]), Pid!token end. procesN(N,Pid,Comp) -> receive token when Comp /= 0 -> io:format('Procs: ~p , token n ~p~n', [N,Comp]), Pid!token, procesN(N, Pid, Comp -1); token when Comp == 0 -> io:format('Finalitza procs ~p~n',[N]) end. %*********************************************************************************************************** anell1(N) -> % Crear el node N io:format('Engego el procs: ~p. Envia missatges a 1~n',[N]), Pid = crearNode1(N-1, self()), io:format("Pid ~p~n",[Pid]), Pid!token, proces1(N,Pid, 3). crearNode1(1, Pid) -> io:format('Engego el procs: 1. Envia missatges a 2~n'), spawn(?MODULE, proces1, [1, Pid, 3]); crearNode1(N, Pid) -> Pidi = spawn(?MODULE, proces1, [N, Pid, 3]), io:format('Engego el procs: ~p. Envia missatges a ~p~n', [N,N+1]), crearNode1(N-1, Pidi). proces1(N,_,0) -> io:format('Finalitza procs ~p~n',[N]); proces1(N, Pid, Comp) -> receive token when Comp /= 0 -> io:format('Procs: ~p , token n ~p~n', [N,Comp]), Pid!token, proces1(N, Pid, Comp -1) end. %**************************************************************************************************************** p(1, N, _) -> PidNext = spawn(?MODULE, p, [2, N, self()]), send_receive(1, PidNext, 3); p(N, N, Pid1) -> receive_send(N, Pid1, 3); p(I, N, Pid1) -> PidNext = spawn(?MODULE, p, [I+1, N, Pid1]), receive_send(I, PidNext, 3). send_receive(I, _, 0) -> io:fwrite("Proc ~b mort~n", [I]); send_receive(I, Pid, N) -> Pid!token, io:fwrite("Proc ~b: token received~n", [I]), receive token -> ok end, send_receive(I, Pid, N-1). receive_send( I, _, 0) -> io:fwrite("Proc ~b mort~n", [I]); %ok; receive_send(I, Pid, N) -> receive token -> ok end, io:fwrite("Proc ~b: token received~n", [I]), Pid!token, receive_send(I, Pid, N-1). start(N) -> spawn(?MODULE, p, [1, N, none]), done.