Skip to content

Instantly share code, notes, and snippets.

@7-fl
Last active May 6, 2017 17:26
Show Gist options
  • Save 7-fl/a35b2d9a078174c5562127ab080a01ab to your computer and use it in GitHub Desktop.
Save 7-fl/a35b2d9a078174c5562127ab080a01ab to your computer and use it in GitHub Desktop.
Convert frequency server to use gen_server using handle_call()

A shell script for running my erlang program:

run.sh:

#!/usr/bin/env sh

erlc -W gf.erl
erl -s gf test2

Then I do

$ chmod u+x run.sh
$ ./run.sh

Erlang creates a separate process for the shell script to run in, so the erlang shell will hang at the end--but that's better than having to type the following a hundred times:

$ erl
Erlang/OTP 19 [erts-8.2] [source] [64-bit] [smp:4:4] [async-threads:10] [hipe] [kernel-poll:false]
Eshell V8.2  (abort with ^G)

1> c(gf).
{ok,gf}

3> gf:test2().
...
...

gf.erl:

-module(gf).
-behavior(gen_server).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).
-export([start/0, allocate/0, deallocate/1, stop/0, client/2, test1/0, test2/0]).

%%====== Server Internal function Replacements ==========

init([]) ->
    {ok, {get_frequencies(), []} }.

get_frequencies() -> [10,11,12,13,14,15].

handle_call(allocate, Client, Freqs) ->
    {NewFreqs, Response} = allocate(Freqs, Client),
    io:format("handle_call(allocate):~n \tFreqs: ~lp~n \tNewFreqs: ~lp~n~n", 
              [Freqs, NewFreqs]),
    {reply, {reply, Response}, NewFreqs};
    
handle_call({deallocate, Freq}, _Client, Freqs) ->
    NewFreqs = deallocate(Freqs, Freq),
    io:format("handle_call(deallocate):~n \tFreqs: ~lp~n \tNewFreqs: ~lp~n~n", 
              [Freqs, NewFreqs]),
    {reply, {reply, ok}, NewFreqs};
    
handle_call(stop, _Pid, Freqs) ->  
    {stop, normal, {reply, stopped}, Freqs}.

terminate(Reason, State) -> 
    io:format("~n~n<====== My Gen Frequency Server Shutdown ======>~n"),
    io:format("Reason: ~w~n", [Reason]),
    io:format("Ending Freqs:~n \t~lp~n", [State]).

%%Template:
handle_cast({reset,N}, _State) -> 
    {noreply, N}.

handle_info(_Info, State) -> 
    {noreply, State}.

code_change(_OldVsn, State, _Extra) -> 
    {ok, State}.

%% ----- No changes to server helper functions -----

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}.

%%==== Server External function Replacements ===

start() ->
    gen_server:start_link(
        {local, ?MODULE},
        ?MODULE, [], []
    ).

allocate() ->
    {reply, Response} = gen_server:call(?MODULE, allocate),
    io:format("client: allocate(): Response: ~w~n", [Response]),
    Response.

deallocate(Freq) ->
    {reply, Response} = gen_server:call(?MODULE, {deallocate, Freq}),
    io:format("client: deallocate(): ~w~n", [Response]),
    Response.

%% stop() ->
%%     Msg = gen_server:stop(?MODULE),
%%     io:format("client:stop(): Response: ~w~n", [Msg]),
%%     Msg.

stop() ->
    {reply, Response} = gen_server:call(?MODULE, stop),
    io:format("stop(): Response: ~w~n", [Response]),
    Response.
    
%%===== TESTS  =======

test2() ->
    start(),
    _Client1 = spawn(?MODULE, client, [1, 1000]),  %% [Id, CallDuration]
    _Client2 = spawn(?MODULE, client, [2, 2000]),
    _Client3 = spawn(?MODULE, client, [3, 3000]),
    timer:sleep(3000),  %%Let clients go at it for awhile
    stop(). 

test1() ->
    start(),
    allocate_loop(8).

allocate_loop(0) ->
    ok;
allocate_loop(N) ->
    allocate(),
    allocate_loop(N-1).

%%======= CLIENT =========

client(Id, Sleep) ->
    handle_allocate_response(allocate(), Id, Sleep),
    client(Id, Sleep).

handle_allocate_response({error, no_frequency}, Id, Sleep) ->
    timer:sleep(500),  %Sleep for a short time before trying again.
    client(Id, Sleep);
handle_allocate_response({ok,Freq}, Id, Sleep) -> 
    timer:sleep(Sleep),  %%Call duration
    deallocate(Freq),
    client(Id, Sleep).



In the shell:

$ ./run.sh
Erlang/OTP 19 [erts-8.2] [source] [64-bit] [smp:4:4] [async-threads:10] [hipe] [kernel-poll:false]

handle_call(allocate):
        Freqs: {[10,11,12,13,14,15],[]}
        NewFreqs: {[11,12,13,14,15],[{10,{<0.58.0>,#Ref<0.0.4.126>}}]}

handle_call(allocate):
        Freqs: {[11,12,13,14,15],[{10,{<0.58.0>,#Ref<0.0.4.126>}}]}
        NewFreqs: {[12,13,14,15],
                   [{11,{<0.59.0>,#Ref<0.0.4.127>}},
                    {10,{<0.58.0>,#Ref<0.0.4.126>}}]}

client: allocate(): Response: {ok,10}
handle_call(allocate):
        Freqs: {[12,13,14,15],
                [{11,{<0.59.0>,#Ref<0.0.4.127>}},
                 {10,{<0.58.0>,#Ref<0.0.4.126>}}]}
        NewFreqs: {[13,14,15],
                   [{12,{<0.60.0>,#Ref<0.0.4.128>}},
                    {11,{<0.59.0>,#Ref<0.0.4.127>}},
                    {10,{<0.58.0>,#Ref<0.0.4.126>}}]}

client: allocate(): Response: {ok,11}
client: allocate(): Response: {ok,12}
Eshell V8.2  (abort with ^G)
1> handle_call(deallocate):
        Freqs: {[13,14,15],
                [{12,{<0.60.0>,#Ref<0.0.4.128>}},
                 {11,{<0.59.0>,#Ref<0.0.4.127>}},
                 {10,{<0.58.0>,#Ref<0.0.4.126>}}]}
        NewFreqs: {[10,13,14,15],
                   [{12,{<0.60.0>,#Ref<0.0.4.128>}},
                    {11,{<0.59.0>,#Ref<0.0.4.127>}}]}

client: deallocate(): ok
handle_call(allocate):
        Freqs: {[10,13,14,15],
                [{12,{<0.60.0>,#Ref<0.0.4.128>}},
                 {11,{<0.59.0>,#Ref<0.0.4.127>}}]}
        NewFreqs: {[13,14,15],
                   [{10,{<0.58.0>,#Ref<0.0.4.144>}},
                    {12,{<0.60.0>,#Ref<0.0.4.128>}},
                    {11,{<0.59.0>,#Ref<0.0.4.127>}}]}

client: allocate(): Response: {ok,10}
handle_call(deallocate):
        Freqs: {[13,14,15],
                [{10,{<0.58.0>,#Ref<0.0.4.144>}},
                 {12,{<0.60.0>,#Ref<0.0.4.128>}},
                 {11,{<0.59.0>,#Ref<0.0.4.127>}}]}
        NewFreqs: {[11,13,14,15],
                   [{10,{<0.58.0>,#Ref<0.0.4.144>}},
                    {12,{<0.60.0>,#Ref<0.0.4.128>}}]}

client: deallocate(): ok
handle_call(allocate):
        Freqs: {[11,13,14,15],
                [{10,{<0.58.0>,#Ref<0.0.4.144>}},
                 {12,{<0.60.0>,#Ref<0.0.4.128>}}]}
        NewFreqs: {[13,14,15],
                   [{11,{<0.59.0>,#Ref<0.0.4.150>}},
                    {10,{<0.58.0>,#Ref<0.0.4.144>}},
                    {12,{<0.60.0>,#Ref<0.0.4.128>}}]}

client: allocate(): Response: {ok,11}
handle_call(deallocate):
        Freqs: {[13,14,15],
                [{11,{<0.59.0>,#Ref<0.0.4.150>}},
                 {10,{<0.58.0>,#Ref<0.0.4.144>}},
                 {12,{<0.60.0>,#Ref<0.0.4.128>}}]}
        NewFreqs: {[10,13,14,15],
                   [{11,{<0.59.0>,#Ref<0.0.4.150>}},
                    {12,{<0.60.0>,#Ref<0.0.4.128>}}]}

client: deallocate(): ok
handle_call(allocate):
        Freqs: {[10,13,14,15],
                [{11,{<0.59.0>,#Ref<0.0.4.150>}},
                 {12,{<0.60.0>,#Ref<0.0.4.128>}}]}
        NewFreqs: {[13,14,15],
                   [{10,{<0.58.0>,#Ref<0.0.4.156>}},
                    {11,{<0.59.0>,#Ref<0.0.4.150>}},
                    {12,{<0.60.0>,#Ref<0.0.4.128>}}]}

client: allocate(): Response: {ok,10}


<====== My Gen Frequency Server Shutdown ======>
Reason: normal
Ending Freqs:
        {[13,14,15],
         [{10,{<0.58.0>,#Ref<0.0.4.156>}},
          {11,{<0.59.0>,#Ref<0.0.4.150>}},
          {12,{<0.60.0>,#Ref<0.0.4.128>}}]}
stop(): Response: stopped



Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment