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.

Share and Enjoy:
  • del.icio.us
  • Reddit
  • Facebook
  • Identi.ca
  • TwitThis

Related posts:

  1. Processes in Erlang
  2. More Erlang: Adding Concurrency
  3. Taking a sip of the AMQP Kool-Aid Part I
  4. Programming Collective intelligence in Erlang

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Search