Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -module(frequency).
- -export([start/0, stop/0, allocate/0, deallocate/2]).
- -export([init/0]).
- %% These are the start functions used to create and
- %% initialize the server.
- start() ->
- register(frequency, spawn(frequency, init, [])).
- init() ->
- Frequencies = {get_frequencies(), []},
- loop(Frequencies).
- % Hard Coded
- get_frequencies() -> [10,11,12,13,14,15].
- %% The client Functions
- stop() -> call(stop).
- allocate() -> call(allocate).
- deallocate(Freq, Pid) -> call({deallocate, Freq, Pid}).
- %% We hide all message passing and the message
- %% protocol in a functional interface.
- call(Message) ->
- frequency ! {request, self(), Message},
- receive
- {reply, Reply} -> Reply
- end.
- %% The Main Loop
- loop(Frequencies) ->
- receive
- {request, Pid, allocate} ->
- {NewFrequencies, Reply} = allocate(Frequencies, Pid),
- reply(Pid, Reply),
- loop(NewFrequencies);
- {request, Pid , {deallocate, Freq}} ->
- NewFrequencies = deallocate(Frequencies, Freq, Pid),
- reply(Pid, ok),
- loop(NewFrequencies);
- {request, Pid, stop} ->
- reply(Pid, ok)
- end.
- reply(Pid, Reply) ->
- Pid ! {reply, Reply}.
- allocate({[], Allocated}, _Pid) ->
- erlang:display(Allocated),
- {{[], Allocated}, {error, no_frequency}};
- allocate({[Freq|Free], Allocated}, Pid) ->
- erlang:display(Allocated),
- {{Free, [{Freq, Pid}|Allocated]}, {ok, Freq}}.
- deallocate({Free, Allocated}, Freq, Pid) ->
- case lists:member({Freq,Pid}, Allocated) of
- true -> NewAllocated=lists:keydelete(Freq, 1, Allocated), {[Freq|Free], NewAllocated};
- false -> {[Free], Allocated}
- end.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement