Created
July 14, 2020 11:50
-
-
Save darcros/695c54f99eb459b1a6d6effd9745f4ce to your computer and use it in GitHub Desktop.
Concurrent Programming in Erlang - The University of Kent - chapter 4.5
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-module(frequency_server). | |
-behaviour(gen_server). | |
-export([init/1, handle_call/3, handle_cast/2]). | |
-export([start/0, stop/0, allocate/0, deallocate/1]). | |
get_frequencies() -> [10,11,12,13,14,15]. | |
%% gen_sever implementation | |
init(_Args) -> | |
Freqs = {get_frequencies(), []}, | |
{ok, Freqs}. | |
handle_call(allocate, _Pid, {[], Allocated}) -> | |
{reply, {error, no_frequency}, {[], Allocated}}; | |
handle_call(allocate, Pid, {[Freq | Free], Allocated}) -> | |
NewFreqs = {Free, [{Freq, Pid} | Allocated]}, | |
{reply, {ok, Freq}, NewFreqs}. | |
handle_cast({deallocate, Freq}, {Free, Allocated}) -> | |
NewAllocated = lists:keydelete(Freq, 1, Allocated), | |
NewFreqs = {[Freq | Free], NewAllocated}, | |
{noreply, NewFreqs}. | |
%% API | |
start() -> | |
gen_server:start_link({local, frequency_server}, ?MODULE, [], []). | |
stop() -> | |
gen_server:stop(?MODULE). | |
allocate() -> | |
gen_server:call(?MODULE, allocate). | |
deallocate(Freq) -> | |
gen_server:cast(?MODULE, {deallocate, Freq}). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice!