Skip to content

Instantly share code, notes, and snippets.

@michaeldperez
Last active April 8, 2017 02:00
Show Gist options
  • Save michaeldperez/bea83ea8285e2ce7a67f54986d214c21 to your computer and use it in GitHub Desktop.
Save michaeldperez/bea83ea8285e2ce7a67f54986d214c21 to your computer and use it in GitHub Desktop.
Frequency Server for Concurrent Programming in Erlang
-module(frequency2).
-export([start/0,allocate/0,deallocate/1,stop/0]).
-export([init/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) ->
%% sleep for 3 sec prior to processing any message to simulate server overload
receive
{request, Pid, allocate} ->
timer:sleep(3000),
{NewFrequencies, Reply} = allocate(Frequencies, Pid),
Pid ! {reply, Reply},
loop(NewFrequencies);
{request, Pid , {deallocate, Freq}} ->
timer:sleep(3000),
NewFrequencies = deallocate(Frequencies, Freq),
Pid ! {reply, ok},
loop(NewFrequencies);
{request, Pid, stop} ->
timer:sleep(3000),
Pid ! {reply, stopped}
end.
%% Functional interface
allocate() ->
frequency2 ! {request, self(), allocate},
receive
{reply, Reply} -> Reply
%% timeout after 2.5 seconds (simulate overload)
after 2500 -> timeout
end,
receive
%% periodically clear mailbox
after 5000 -> clear()
end.
deallocate(Freq) ->
frequency2 ! {request, self(), {deallocate, Freq}},
receive
{reply, Reply} -> Reply
%% timeout after 2.5 seconds (simulate overload)
after 2500 -> timeout
end,
receive
%% periodically clear mailbox
after 5000 -> clear()
end.
stop() ->
frequency2 ! {request, self(), stop},
receive
{reply, Reply} -> Reply
end.
%% Flush all messages in mailbox
clear() ->
receive
Msg ->
io:format("Delayed Message: ~w~n", [Msg]),
clear()
after 0 -> ok
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}.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment