Skip to content

Instantly share code, notes, and snippets.

@michaeldperez
Created August 22, 2017 04:07
Show Gist options
  • Save michaeldperez/a6f70de2ebe9453e2ab0655496e499ca to your computer and use it in GitHub Desktop.
Save michaeldperez/a6f70de2ebe9453e2ab0655496e499ca to your computer and use it in GitHub Desktop.
frequency server
-module(frequency2).
-export([start/0,allocate/0,deallocate/1,stop/0]).
-export([init/0]).
start() ->
register(frequency2,
spawn(frequency2, init, [])).
init() ->
Frequencies = {get_frequencies(), []},
loop(Frequencies).
get_frequencies() -> [10,11,12,13,14,15].
loop(Frequencies) ->
receive
{request, Pid, allocate} ->
timer:sleep(5500),
{NewFrequencies, Reply} = allocate(Frequencies, Pid),
Pid ! {reply, Reply},
loop(NewFrequencies);
{request, Pid , {deallocate, Freq}} ->
timer:sleep(5500),
NewFrequencies = deallocate(Frequencies, Freq),
Pid ! {reply, ok},
loop(NewFrequencies);
{request, Pid, stop} ->
Pid ! {reply, stopped}
end.
allocate() ->
%% Request frequency but timeout after 5 seconds
frequency2 ! {request, self(), allocate},
receive
{reply, Reply} -> Reply
after 5000 -> clear()
end.
%% Deallocate frequency but timeout after 5 seconds
deallocate(Freq) ->
frequency2 ! {request, self(), {deallocate, Freq}},
receive
{reply, Reply} -> Reply
after 5000 -> clear()
end.
stop() ->
frequency2 ! {request, self(), stop},
receive
{reply, Reply} -> Reply
end.
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}.
%% Flush mailbox (ends process afterward)
clear() ->
receive
Msg ->
io:format("Delayed Message: ~w~n", [Msg]),
clear()
after 0 -> timeout
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment