Skip to content

Instantly share code, notes, and snippets.

@naoyat
Created February 4, 2010 08:31
Show Gist options
  • Save naoyat/294452 to your computer and use it in GitHub Desktop.
Save naoyat/294452 to your computer and use it in GitHub Desktop.
Programming Erlang, Problem 8.11
-module(ring).
-export([body/2]).
for(N,N,F) -> [F()];
for(I,N,F) -> [F()|for(I+1,N,F)].
for1(N,N,F) -> [F(N)];
for1(I,N,F) -> [F(I)|for1(I+1,N,F)].
baton() ->
receive
{set, Next, Incr} ->
baton(Next,Incr);
{baton,_J,_M} ->
io:format("I don't know the next one.~n"),
baton()
end.
baton(Next,false) ->
receive
Any ->
% io:format(" -"),
Next ! Any,
baton(Next,false)
end;
baton(Next,true) ->
receive
{baton,Caller,M,M} ->
% io:format(" +|~n"),
Caller ! done;
{baton,Caller,J,M} ->
% io:format(" +~n"),
Next ! {baton,Caller,J+1,M},
baton(Next,true)
end.
body(N,M) ->
statistics(runtime),
statistics(wall_clock),
Batons = for(1,N,fun() -> spawn(fun baton/0) end),
for1(1,N,
fun(I) ->
Ith = lists:nth(I,Batons),
Next = lists:nth((I rem N)+1,Batons),
Ith ! {set,Next,I==N}
end),
[First|_] = Batons,
{_, Time1} = statistics(runtime),
{_, Time2} = statistics(wall_clock),
io:format("Preparation time=~p (~p) msec~n", [Time1, Time2]),
statistics(runtime),
statistics(wall_clock),
First ! {baton,self(),1,M},
receive
done ->
{_, Time3} = statistics(runtime),
{_, Time4} = statistics(wall_clock),
io:format("Process time=~p (~p) msec~n", [Time3, Time4])
end.
-module(ring).
-export([body/2]).
for(N,N,F) -> [F()];
for(I,N,F) -> [F()|for(I+1,N,F)].
for1(N,N,F) -> [F(N)];
for1(I,N,F) -> [F(I)|for1(I+1,N,F)].
baton() ->
receive
{set, Next, Caller, Incr} ->
baton(Next,Caller,Incr);
{baton,_J,_M} ->
io:format("I don't know the next one.~n"),
baton()
end.
baton(Next,Caller,false) ->
receive
Any ->
% io:format(" -"),
Next ! Any,
baton(Next,Caller,false)
end;
baton(Next,Caller,true) ->
receive
{baton,M,M} ->
% io:format(" +|~n"),
Caller ! done;
{baton,J,M} ->
% io:format(" +~n"),
Next ! {baton,J+1,M},
baton(Next,Caller,true)
end.
body(N,M) ->
statistics(runtime),
statistics(wall_clock),
Batons = for(1,N,fun() -> spawn(fun baton/0) end),
Caller = self(),
for1(1,N,
fun(I) ->
Ith = lists:nth(I,Batons),
Next = lists:nth((I rem N)+1,Batons),
Ith ! {set,Next,Caller,I==N}
end),
[First|_] = Batons,
{_, Time1} = statistics(runtime),
{_, Time2} = statistics(wall_clock),
io:format("Preparation time=~p (~p) msec~n", [Time1, Time2]),
statistics(runtime),
statistics(wall_clock),
First ! {baton,1,M},
receive
done ->
{_, Time3} = statistics(runtime),
{_, Time4} = statistics(wall_clock),
io:format("Process time=~p (~p) msec~n", [Time3, Time4])
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment