Skip to content

Instantly share code, notes, and snippets.

@fswalker
Last active April 9, 2017 21:45
Show Gist options
  • Save fswalker/71937a1b322c417542e80f5128889c50 to your computer and use it in GitHub Desktop.
Save fswalker/71937a1b322c417542e80f5128889c50 to your computer and use it in GitHub Desktop.
%% Based on code from
%% Erlang Programming
%% Francecso Cesarini and Simon Thompson
%% O'Reilly, 2008
%% http://oreilly.com/catalog/9780596518189/
%% http://www.erlangprogramming.org/
%% (c) Francesco Cesarini and Simon Thompson
-module(frequency2).
-export([start/0,allocate/0,deallocate/1,stop/0]).
-export([init/0]).
-export([ clear/0
, test/0
]).
%% These are the start functions used to create and
%% initialize the server.
start() ->
register(frequency2,
spawn(frequency2, init, [])).
init() ->
Frequencies = {get_frequencies(), []},
loop(Frequencies).
% Hard Coded
get_frequencies() -> [10,11,12,13,14,15].
%% The Main Loop
loop(Frequencies) ->
receive
{request, Pid, allocate} ->
{NewFrequencies, Reply} = allocate(Frequencies, Pid),
% sleep below causes client time out
timer:sleep(1500),
Pid ! {reply, Reply},
loop(NewFrequencies);
{request, Pid , {deallocate, Freq}} ->
NewFrequencies = deallocate(Frequencies, Freq),
% sleep below does not caus client time out
timer:sleep(500),
Pid ! {reply, ok},
loop(NewFrequencies);
{request, Pid, stop} ->
timer:sleep(1500),
Pid ! {reply, stopped}
end.
%% Functional interface
allocate() ->
clear(),
frequency2 ! {request, self(), allocate},
receive
{reply, Reply} -> Reply
after 1000 ->
io:format("Allocate timed out~n"),
{error, time_out}
end.
deallocate(Freq) ->
clear(),
frequency2 ! {request, self(), {deallocate, Freq}},
receive
{reply, Reply} -> Reply
after 1000 ->
io:format("Deallocate freq ~w timed out~n", [Freq]),
{error, time_out}
end.
stop() ->
clear(),
frequency2 ! {request, self(), stop},
receive
{reply, Reply} -> Reply
after 1000 ->
io:format("Stop timed out~n"),
{error, time_out}
end.
clear() ->
receive
Msg ->
io:format("Clear msg: ~w~n", [Msg]),
clear()
after 0 ->
{done}
end.
%% The Internal Help Functions used to allocate and
%% deallocate frequencies.
allocate({[], Allocated}, _Pid) ->
{{[], Allocated}, {error, no_frequency}};
allocate({[Freq|Free], Allocated}, Pid) ->
{{Free, [{Freq, Pid}|Allocated]}, {ok, Freq}}.
deallocate({Free, Allocated}, Freq) ->
NewAllocated=lists:keydelete(Freq, 1, Allocated),
{[Freq|Free], NewAllocated}.
test () ->
start(),
R1 = allocate(),
io:format("~w~n", [R1]),
R2 = allocate(),
io:format("~w~n", [R2]),
R3 = deallocate(10),
io:format("~w~n", [R3]),
R4 = deallocate(11),
io:format("~w~n", [R4]),
R5 = deallocate(22),
io:format("~w~n", [R5]),
R6 = allocate(),
io:format("~w~n", [R6]),
S = stop(),
io:format("~w~n", [S]).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment