Here’s my solution for the N processes in a star concurrency exercise, you can run the program by calling the main function—comments appreciated.
-module(star).
-export([main/3, vertex_node/0, center_node/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.
vertex_node() ->
receive
{stop, Center_PID} ->
io:format("recieved ~w, from ~w, exiting~n", [stop, Center_PID]),
exit(ok);
{Something, Center_PID} ->
io:format("recieved message: ~s, from ~w~n", [Something, Center_PID]),
Center_PID ! {self(), ok},
vertex_node()
end.
center_node(_, _, 0, Original_Nodes ) ->
lists:map(fun(Vertex_Node) -> Vertex_Node ! {stop, self()} end, Original_Nodes);
center_node(Message, [], Count, Origingal_Nodes) ->
center_node(Message, Origingal_Nodes, Count -1, Origingal_Nodes);
center_node(Message, Nodes, Count, Original_Node_List) ->
[Vertex_Node | Remaining_Nodes] = Nodes,
Vertex_Node ! {Message, self()},
receive
{Pid, Msg} ->
io:format("center received ack: ~w, from ~w~n", [Msg, Pid])
end,
center_node(Message, Remaining_Nodes, Count, Original_Node_List).
main(Processes, Messages, Message) ->
Nodes = lists:map(fun(X) -> spawn(star, vertex_node, []) end, lists:seq(1, Processes)),
spawn(star, center_node, [Message, Nodes, Messages, Nodes]).
A nicely formatted version is available here.
P.S. If anyone knows how to do add syntax highlighting for Erlang to Windows Live Writer, please let me know.
Related posts:





Leave a Reply