%% now it's exactly as the example #3 here: %% http://www.erlang.org/course/exercises.html#conc -Module(star2). -export([go/3, build_ring/2, proc/0, send/4]). %% Write a function which starts N processes in a star, and sends a message to %% each of them M times. After the messages have been sent the processes %% should terminate gracefully. % 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(star2, 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 - 1, Orig_Pid_List); send(Msg, [Next_PID | Rest], N, Orig_Pid_List) -> Next_PID ! {self(), Msg}, receive {Pid, Msg} -> io:format("received from ~w, ~w~n", [Pid, N]), send(Msg, Rest, N, 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).