Skip to content

Instantly share code, notes, and snippets.

@vlasenkoalexey
Created April 12, 2017 05:53
Show Gist options
  • Save vlasenkoalexey/319859f81840631fb74e1395449ac585 to your computer and use it in GitHub Desktop.
Save vlasenkoalexey/319859f81840631fb74e1395449ac585 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
%% cd("C:/Users/Alexey/Documents/ErlangClass").
-module(frequency).
-export([start/0,allocate/0,deallocate/1,stop/0]).
-export([init/0,clear/0]).
%% These are the start functions used to create and
%% initialize the server.
start() ->
register(frequency,
spawn(frequency, 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),
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.
%% Functional interface
allocate() ->
clear(), % clear all messages
frequency ! {request, self(), allocate},
receive
{reply, Reply} -> Reply
after 500 ->
timeout %% reply with timeout atom
end.
deallocate(Freq) ->
clear(), % clear all messages
frequency ! {request, self(), {deallocate, Freq}},
receive
{reply, Reply} -> Reply
after 500 ->
timeout %% reply with timeout atom
end.
stop() ->
frequency ! {request, self(), stop},
receive
{reply, Reply} -> Reply
end.
%% The Internal Help Functions used to allocate and
%% deallocate frequencies.
allocate({[], Allocated}, _Pid) ->
timer:sleep(rand:uniform(1000)), %% simulating load which could cause timeout
{{[], Allocated}, {error, no_frequency}};
allocate({[Freq|Free], Allocated}, Pid) ->
timer:sleep(rand:uniform(1000)), %% simulating load which could cause timeout
{{Free, [{Freq, Pid}|Allocated]}, {ok, Freq}}.
deallocate({Free, Allocated}, Freq) ->
timer:sleep(rand:uniform(1000)), %% simulating load which could cause timeout
NewAllocated=lists:keydelete(Freq, 1, Allocated),
{[Freq|Free], NewAllocated}.
%% clear function - similar to one
clear() ->
receive
Msg ->
io:format("cleared message: ~w~n", [Msg]),
clear()
after 0 ->
ok
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment