Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -module(top).
- -behaviour(gen_server).
- -export([start_link/1]).
- -export([allocate/0, free/1, exclude/2]).
- -export([handle_call/3, handle_cast/2, init/1]).
- -record(state, {free = [], allocated = dict:new()}).
- start_link(Resources) ->
- gen_server:start_link({local, top}, top, [Resources], []).
- init([Resources]) ->
- {ok, #state{free = Resources}}.
- handle_call(allocate, _From, #state{free = []} = State) ->
- {reply, nothing_to_allocate, State};
- handle_call(allocate, {Pid, _}, #state{free = [Resource|Free], allocated = Allocated}) ->
- link(Pid),
- Allocated1 = dict:append(Pid, Resource, Allocated),
- {reply, {allocated, Resource}, #state{free = Free, allocated = Allocated1}};
- handle_call({free, Resource}, {Pid, _}, #state{free = Free, allocated = Allocated} = State) ->
- case dict:find(Pid, Allocated) of
- error -> {reply, nothing_allocate_by_you, State};
- {ok, ProcessResources} ->
- Free1 = [Resource|Free],
- case exclude(Resource, ProcessResources) of
- error -> {reply, not_your_resource, State};
- {ok, []} ->
- unlink(Pid),
- Allocated1 = dict:erase(Pid, Allocated),
- {reply, freed, #state{free = Free1, allocated = Allocated1}};
- {ok, ProcessResources1} ->
- Allocated1 = dict:store(Pid, ProcessResources1, Allocated),
- {reply, freed, #state{free = Free1, allocated = Allocated1}}
- end
- end.
- exclude(_, []) -> error;
- exclude(E, [E|T]) -> {ok, T};
- exclude(E, [H|T]) ->
- case exclude(E, T) of
- error -> error;
- {ok, T1} -> {ok, [H|T1]}
- end.
- handle_cast(Request, _State) ->
- throw({no_casts, Request}).
- allocate() ->
- gen_server:call(top, allocate).
- free(Resource) ->
- gen_server:call(top, {free, Resource}).
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement