Erlang Exercises: Interaction between processes, Concurrency: Star of Processes

Posted by sudothinker on March 02, 2009

Here is my solution to the last of the 3 Erlang ‘Interaction between processes, concurrency’ problems here: http://erlang.org/course/exercises.html#conc. It is definitely much shorter than my ring code.

Here are some things I assumed from the problem statement:

  • The center node is the main process and is not spawned.
  • The center node continues to send messages to the star nodes regardless of the response. It doesn’t wait for the response to send another message.
-module(star).
-export([star/2, star_node/1]).

% 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.
star(N, M) ->
  Nodes = lists:map(fun(X) -> spawn(star, star_node, [self()]) end, lists:seq(1, N)),
  io:format("Built nodes ~w~n", [Nodes]),    
  send(M, Nodes).

% Sends a ping +M+ times to each of the nodes in +Nodes+
send(0, Nodes) ->
  lists:flatmap(fun(X) -> X ! {self(), stop}, [X] end, Nodes);
send(M, Nodes) when M > 0 ->
  lists:flatmap(fun(X) -> X ! {self(), ping}, [X] end, Nodes),
  send(M - 1, Nodes).

% An element of the star, receives messages from +Center+ and sends them back
star_node(Center) ->
  receive
    {Center, ping} ->
      io:format("~w recieved a ping, sending it back to ~w~n", [self(), Center]),
      Center ! ping,
      star_node(Center);
    {Center, stop} ->
      io:format("~w recieved a stop~n", [self()]),
      true
  end.

Comments

Leave a response

Comment