[erlang-questions] code sample request

Wallentin Dahlberg wallentin.dahlberg@REDACTED
Mon Jan 18 17:45:40 CET 2010


Another one,

-module(ring).
-export([run/2, run/3]).

run(N, M) -> run(N, M, msg).
run(N, M, Msg) -> run(N - 1, M, Msg, self()).

run(0, 0, _, _) -> ok;
run(0, M, Msg, Pid) ->
    Pid ! {self(), Msg},
    receive {_From, Msg} -> run(0, M - 1, Msg, Pid) end;
run(N, M, Msg, Pid) -> run(N - 1, M, Msg, spawn_link(fun() -> loop(Pid)
end)).

loop(To) ->
    receive
        {From, Msg} ->
            io:format("~p -> (Me:~p) -> ~p~n", [From, self(), To]),
            To ! {self(), Msg},
            loop(To)
    end.


Beware of typos and other confusing errors. =)

// egil

2010/1/18 Fred Hebert <mononcqc@REDACTED>

> On Mon, Jan 18, 2010 at 10:26 AM, Ish Rattan <ishwar@REDACTED
> >wrote:
>
> >
> > I am trying to write the code for
> > "Create N processes in a ring. Send a message
> > around the ring M times so that a total of N*M
> > messages get sent." problem from Armstrong's book.
> >
> > A solution code wiil be appreciated.
> >
> > -ishwar
> >
> >
> > ________________________________________________________________
> > erlang-questions mailing list. See http://www.erlang.org/faq.html
> > erlang-questions (at) erlang.org
> >
> > See
>
> http://shootout.alioth.debian.org/u64/benchmark.php?test=threadring&lang=hipe&id=1for
> a common efficient implementation.
>


More information about the erlang-questions mailing list