Skip to content

Instantly share code, notes, and snippets.

@rajapaju
Created April 23, 2017 15:24
Show Gist options
  • Save rajapaju/2ef8c7cc8ecd64550f464ad153f2e14b to your computer and use it in GitHub Desktop.
Save rajapaju/2ef8c7cc8ecd64550f464ad153f2e14b 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(frequency).
-export([start/0,restarter/0,init/0,allocate/0,deallocate/1,stop/0]).
%%%%%% Assigment related code
% Start frequency supervisor
start() ->
register(frequency_sub, spawn(?MODULE, restarter, [])).
% frequency process restarter.
restarter() ->
process_flag(trap_exit, true),
Pid = spawn_link(?MODULE, init, []),
register(?MODULE, Pid),
receive
{'EXIT', Pid, normal} -> % not a crash
ok;
{'EXIT', Pid, shutdown} -> % manual termination, not a crash
ok;
{'EXIT', Pid, _} ->
restarter()
end.
%%%%%% End of assignment
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} ->
% Overloaded allocate
% timer:sleep(5000),
{NewFrequencies, Reply} = allocate(Frequencies, Pid),
Pid ! {reply, Reply},
loop(NewFrequencies);
{request, Pid , {deallocate, Freq}} ->
NewFrequencies = deallocate(Frequencies, Freq),
Pid ! {reply, ok},
loop(NewFrequencies);
{request, Pid, stop} ->
Pid ! {reply, stopped}
end.
clear() ->
receive
_Msg ->
io:format("Clear: ~n"),
clear()
after 0 ->
true
end.
%% Functional interface
%% timeout 1000ms
allocate() ->
%clean mailbox before allocating new.
clear(),
frequency ! {request, self(), allocate},
receive
{reply, Reply} -> Reply
after 1000 ->
{error, timeout}
end.
deallocate(Freq) ->
%clean mailbox before deallocating new.
clear(),
frequency ! {request, self(), {deallocate, Freq}},
receive
{reply, Reply} -> Reply
after 1000 ->
{error, timeout}
end.
stop() ->
frequency ! {request, self(), stop},
receive
{reply, Reply} -> Reply
after 1000 ->
{error, timeout}
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),
{
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment