Advertisement
Guest User

Untitled

a guest
Nov 18th, 2019
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.56 KB | None | 0 0
  1. -module(frequency).
  2. -export([start/0, stop/0, allocate/0, deallocate/2]).
  3. -export([init/0]).
  4. %% These are the start functions used to create and
  5. %% initialize the server.
  6. start() ->
  7. register(frequency, spawn(frequency, init, [])).
  8. init() ->
  9. Frequencies = {get_frequencies(), []},
  10. loop(Frequencies).
  11. % Hard Coded
  12. get_frequencies() -> [10,11,12,13,14,15].
  13. %% The client Functions
  14. stop() -> call(stop).
  15. allocate() -> call(allocate).
  16. deallocate(Freq, Pid) -> call({deallocate, Freq, Pid}).
  17. %% We hide all message passing and the message
  18. %% protocol in a functional interface.
  19. call(Message) ->
  20. frequency ! {request, self(), Message},
  21. receive
  22. {reply, Reply} -> Reply
  23. end.
  24. %% The Main Loop
  25. loop(Frequencies) ->
  26. receive
  27. {request, Pid, allocate} ->
  28. {NewFrequencies, Reply} = allocate(Frequencies, Pid),
  29. reply(Pid, Reply),
  30. loop(NewFrequencies);
  31. {request, Pid , {deallocate, Freq}} ->
  32. NewFrequencies = deallocate(Frequencies, Freq, Pid),
  33. reply(Pid, ok),
  34. loop(NewFrequencies);
  35. {request, Pid, stop} ->
  36. reply(Pid, ok)
  37. end.
  38. reply(Pid, Reply) ->
  39. Pid ! {reply, Reply}.
  40. allocate({[], Allocated}, _Pid) ->
  41. erlang:display(Allocated),
  42. {{[], Allocated}, {error, no_frequency}};
  43. allocate({[Freq|Free], Allocated}, Pid) ->
  44. erlang:display(Allocated),
  45. {{Free, [{Freq, Pid}|Allocated]}, {ok, Freq}}.
  46. deallocate({Free, Allocated}, Freq, Pid) ->
  47. case lists:member({Freq,Pid}, Allocated) of
  48. true -> NewAllocated=lists:keydelete(Freq, 1, Allocated), {[Freq|Free], NewAllocated};
  49. false -> {[Free], Allocated}
  50. end.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement