aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorNathan Lasseter <nathan.je.lasseter@googlemail.com>2011-01-27 21:26:50 +0000
committerNathan Lasseter <nathan.je.lasseter@googlemail.com>2011-01-27 21:26:50 +0000
commit9a2c34399e40e9b27080e118f183a2b8058d04b0 (patch)
treeb608434461c12af21bab51aa4e2728a52b4bcc0e
Initial commit
-rw-r--r--erlbal.erl51
1 files changed, 51 insertions, 0 deletions
diff --git a/erlbal.erl b/erlbal.erl
new file mode 100644
index 0000000..417eb1c
--- /dev/null
+++ b/erlbal.erl
@@ -0,0 +1,51 @@
+-module(erlbal).
+-export([make_request/0, start_bal/0, kill_bal/0, start_server/1]).
+
+start_server(ID) ->
+ PID = spawn(fun() -> serverloop(ID) end),
+ balancer ! {add_node, PID}.
+
+serverloop(ID) ->
+ receive
+ {request, From} ->
+ balancer ! {response, From, ID},
+ serverloop(ID);
+ die ->
+ ok
+ end.
+
+start_bal() ->
+ register(balancer, spawn(fun() -> balloop([], 1) end)).
+
+kill_bal() ->
+ balancer ! die.
+
+balloop(Serverlist, Nextserver) ->
+ receive
+ {add_node, PID} ->
+ balloop(Serverlist ++ [PID], Nextserver);
+ {request, From} ->
+ Serv = lists:nth(Nextserver, Serverlist),
+ Serv ! {request, From},
+ NS = Nextserver + 1,
+ SLL = length(Serverlist),
+ if
+ NS > SLL ->
+ balloop(Serverlist, 1);
+ true ->
+ balloop(Serverlist, Nextserver+1)
+ end;
+ {response, To, ID} ->
+ To ! ID,
+ balloop(Serverlist, Nextserver);
+ die ->
+ lists:foreach(fun(X) -> X ! die end, Serverlist)
+ end.
+
+
+make_request() ->
+ balancer ! {request, self()},
+ receive
+ ID ->
+ ID
+ end.