Exercise 4-2
July 3rd 2009 04:52 pm
This particular problem comes from the book Erlang Programming published in 2009 by O’reilly, it is the ring message problem (ring.erl).
It took me a while to do this problem because this is my first foray into concurrency, and I’m not used to the way they pass information around (always tries to pass information in function parameters). However, after a few failed iterations, this is my solution. It is not as elegant as some of the solution online, and the best one I’ve seen uses foldr to shorten the program.
If there is any questions/problems regarding my code, please don’t hesitate and ask in the comments!
-module(ring). -export([start/3, construct/4, loop/2]). start(M, N, Msg) -> io:format("~p Testing ~p~n", [self(), Msg]), spawn(ring, construct, [true, N, M, Msg]). construct(true, Count, M, Msg) -> Pid = spawn(ring, construct, [self(), Count-1, M, Msg]), loop(Pid, M); construct(First, 0, _, Msg) -> First ! Msg; construct(First, 1, M, Msg) -> spawn(ring, construct, [First, 0, M, Msg]), loop(First, M); construct(First, Count, M, Msg) -> Pid = spawn(ring, construct, [First, Count-1, M, Msg]), loop(Pid, M). loop(Next, 0) -> io:format("~p Stopping~n", [self()]), Next ! stop; loop(Next, M) -> receive stop -> io:format("~p Stopping Abornomally~n", [self()]), true; Msg -> io:format("~p Received ~p~n", [self(), Msg]), Next ! Msg, loop(Next, M-1) end.