Last active

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist
View race.erl
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
#!/usr/bin/env escript
%% -*- erlang -*-
%%! +P 100000000
-module(race).
-mode(compile).
-export([main/1]).
 
main(Args) ->
[NumThreads, NumRunners] = [list_to_integer(Arg) || Arg <- Args],
Parent = self(),
RacerA = spawn_link(fun() -> race(Parent, NumRunners, NumThreads) end),
RacerB = spawn_link(fun() -> race(Parent, NumRunners, NumThreads) end),
receive
{RacerA, Res} ->
io:format("A won: ~p~n", [Res]);
{RacerB, Res} ->
io:format("B won: ~p~n", [Res])
end,
halt(0).
 
 
race(Parent, NumRunners, NumThreads) ->
io:format("making tracks~n"),
First = make_tracks(self(), 0, NumThreads),
io:format("sending runners~n"),
send_runners(First, NumRunners),
io:format("waiting for finishers~n"),
Parent ! {self(), recv_runners(NumRunners)}.
 
make_tracks(Parent, 0, N) ->
Pid = spawn_link(fun() -> last_track(Parent) end),
make_tracks(Pid, 1, N);
make_tracks(Parent, N, N) ->
spawn_link(fun() -> track(Parent) end);
make_tracks(Parent, N, Max) ->
Pid = spawn_link(fun() -> track(Parent) end),
make_tracks(Pid, N+1, Max).
 
 
send_runners(_, 0) -> ok;
send_runners(Pid, N) ->
Pid ! {from, self(), N},
send_runners(Pid, N-1).
 
track(To) ->
receive
{from, Parent, N} ->
To ! {from, self(), N},
track(To, Parent)
end.
 
track(To, Parent) ->
receive
{from, Parent, N} -> To ! {from, self(), N};
{back, N} -> Parent ! {back, N}
end,
track(To, Parent).
 
last_track(To) ->
receive
{from, Parent, N} -> Parent ! {back, N}
end,
last_track(To).
 
recv_runners(N) -> recv_runners(N,[]).
 
recv_runners(0, Acc) -> lists:reverse(Acc);
recv_runners(N, Acc) ->
receive
{back, Runner} -> recv_runners(N-1, [Runner|Acc])
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.