Advertisement
Guest User

Untitled

a guest
Nov 20th, 2018
1,035
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Erlang 1.92 KB | None | 0 0
  1. %% Code from
  2. %%   Erlang Programming
  3. %%   Francecso Cesarini and Simon Thompson
  4. %%   O'Reilly, 2008
  5. %%   http://oreilly.com/catalog/9780596518189/
  6. %%   http://www.erlangprogramming.org/
  7. %%   (c) Francesco Cesarini and Simon Thompson
  8.  
  9. -module(frequency).
  10. -export([start/0, stop/0, allocate/0, deallocate/1]).
  11. -export([init/0]).
  12.  
  13. %% These are the start functions used to create and
  14. %% initialize the server.
  15.  
  16. start() ->
  17.   register(frequency, spawn(frequency, init, [])).
  18.  
  19. init() ->
  20.   Frequencies = {get_frequencies(), []},
  21.   loop(Frequencies).
  22.  
  23. % Hard Coded
  24. get_frequencies() -> [10,11,12,13,14,15].
  25.  
  26. %%  The client Functions
  27.  
  28. stop()           -> call(stop).
  29. allocate()       -> call(allocate).
  30. deallocate(Freq) -> call({deallocate, Freq}).
  31.  
  32. %% We hide all message passing and the message
  33. %% protocol in a functional interface.
  34.  
  35. call(Message) ->
  36.   frequency ! {request, self(), Message},
  37.   receive
  38.     {reply, Reply} -> Reply
  39.   end.
  40.  
  41. %% The Main Loop
  42.  
  43. loop(Frequencies) ->
  44.   receive
  45.     {request, Pid, allocate} ->
  46.       {NewFrequencies, Reply} = allocate(Frequencies, Pid),
  47.       reply(Pid, Reply),
  48.       loop(NewFrequencies);
  49.     {request, Pid , {deallocate, Freq}} ->
  50.       NewFrequencies = deallocate(Frequencies, Freq,Pid),
  51.       reply(Pid, ok),
  52.       loop(NewFrequencies);
  53.     {request, Pid, stop} ->
  54.       reply(Pid, ok)
  55.   end.
  56.  
  57. reply(Pid, Reply) ->
  58.   Pid ! {reply, Reply}.
  59.  
  60. %% The Internal Help Functions used to allocate and
  61. %% deallocate frequencies.
  62.  
  63. allocate({[], Allocated}, _Pid) ->
  64.   {{[], Allocated}, {error, no_frequences}};
  65. allocate({[Freq|Free], Allocated}, Pid) ->
  66.   {{Free, [{Freq, Pid}|Allocated]}, {ok, Freq}}.
  67.  
  68. deallocate({Free, Allocated}, Freq,Pid) ->
  69.     case lists:keyfind(Freq, 1, Allocated) of
  70.             {Freq, Pid} ->
  71.                 NewAllocated=lists:keydelete(Freq, 1, Allocated),
  72.                 {[Freq|Free],  NewAllocated};
  73.             false -> {Free,  Allocated};
  74.             _ -> {Free,  Allocated}
  75.     end.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement