Chapter 8 Problems
Christopher ...
1 post
|
Hi all! Man, I’m loving Erlang. It’s nice to be excited about programming again. Thanks JOE!! I completed problem 2, and I was hoping someone might give me some pointers. |
Alain O'Dea
35 posts
|
I posted a reply to your blog, but it was dark and appears to have been eaten by a grue :( |
Nico Verwer
1 post
|
Hello all. I did not do the second part of problem 2, because I don’t have a blog. The solution I came up with is a bit different from what I have seen in blogs, so I thought I’d post it here.
-module(c8p2).
-export([start/2]).
start(Rounds, Size) ->
Ring = ring(Size-1, self()), %% Set up a ring of Size-1, because self() will participate.
statistics(runtime),
Ring ! {ping, Rounds}, %% Send the ping into the ring.
main(Ring), %% Put myself into the ring.
{_, Runtime} = statistics(runtime),
io:format("Ringing ~p messages took ~p milliseconds~n", [Rounds * Size, Runtime]).
%% Create a ring of specified size. Boss is the start of the ring.
ring(1, Boss) ->
spawn(fun() -> proc(1, Boss) end);
ring(N, Boss) ->
spawn(fun() -> proc(N, ring(N-1, Boss)) end).
%% Proc is a process in the ring. N is its number in the ring, Next is the next process.
proc(N, Next) ->
receive
{ping, M} -> %% M is the message number.
Next ! {ping, M}, %% Propagate the message.
if
M > 1 -> proc(N, Next); %% Expect more messages.
true -> ready %% We're done.
end
end.
%% Main is similar to proc, but decrements the message number.
%% Returns when all messages have been sent.
main(Next) ->
receive
{ping, M} ->
if
M > 1 ->
Next ! {ping, M-1},
main(Next);
true -> ready
end
end.
|
Alain O'Dea
35 posts
|
Hi Nico, You have an interesting and concise solution there. I like the idea of having a single different process in the ring that decrements the message number. Nice work! |
4 posts, 3 voices
