-module(star). -export([go/3, build_ring/2, proc/0, send/4]). %% recreates this: http://www.erlang.org/course/ex3.gif % build a list of pids while starting the processes % build(N, L) where N is the number of processes to spawn % and L the list to append to build_ring(0, L) -> L; build_ring(N, L) -> List = lists:append(L, [spawn(star, proc, [])]), build_ring(N - 1, List). % send the message across the ring surrounding the process % in the center (the main process). If the list of processes % gets empty a loop is done so start again. When the count % of bounces reaches 0 we're done. send(_, _, 0, _) -> exit(normal); send(Msg, [], N, Orig_Pid_List) -> send(Msg, Orig_Pid_List, N, Orig_Pid_List); send(Msg, [Next_PID | Rest], N, Orig_Pid_List) -> Next_PID ! {self(), Msg}, io:format("sent to ~w~n", [Next_PID]), receive {Pid, Msg} -> io:format("received from ~w~n", [Pid]), send(Msg, Rest, N - 1, Orig_Pid_List) end. % proc identifies the node, it only has to bounce the message % and go back to listen proc() -> receive {Pid, Msg} -> Pid ! {self(), Msg}, proc() end. % the entry point of the program. go(Num_Processes, Num_Bounces, Msg) -> Pid_List = build_ring(Num_Processes, []), io:format("built ~w processes.~n", [Num_Processes]), send(Msg, Pid_List, Num_Bounces, Pid_List).