Advertisement
Guest User

Untitled

a guest
Feb 23rd, 2019
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.82 KB | None | 0 0
  1. -module(top).
  2. -behaviour(gen_server).
  3.  
  4. -export([start_link/1]).
  5. -export([allocate/0, free/1, exclude/2]).
  6. -export([handle_call/3, handle_cast/2, init/1]).
  7.  
  8. -record(state, {free = [], allocated = dict:new()}).
  9.  
  10. start_link(Resources) ->
  11. gen_server:start_link({local, top}, top, [Resources], []).
  12.  
  13. init([Resources]) ->
  14. {ok, #state{free = Resources}}.
  15.  
  16. handle_call(allocate, _From, #state{free = []} = State) ->
  17. {reply, nothing_to_allocate, State};
  18.  
  19. handle_call(allocate, {Pid, _}, #state{free = [Resource|Free], allocated = Allocated}) ->
  20. link(Pid),
  21. Allocated1 = dict:append(Pid, Resource, Allocated),
  22. {reply, {allocated, Resource}, #state{free = Free, allocated = Allocated1}};
  23.  
  24. handle_call({free, Resource}, {Pid, _}, #state{free = Free, allocated = Allocated} = State) ->
  25. case dict:find(Pid, Allocated) of
  26. error -> {reply, nothing_allocate_by_you, State};
  27. {ok, ProcessResources} ->
  28. Free1 = [Resource|Free],
  29. case exclude(Resource, ProcessResources) of
  30. error -> {reply, not_your_resource, State};
  31. {ok, []} ->
  32. unlink(Pid),
  33. Allocated1 = dict:erase(Pid, Allocated),
  34. {reply, freed, #state{free = Free1, allocated = Allocated1}};
  35. {ok, ProcessResources1} ->
  36. Allocated1 = dict:store(Pid, ProcessResources1, Allocated),
  37. {reply, freed, #state{free = Free1, allocated = Allocated1}}
  38. end
  39. end.
  40.  
  41. exclude(_, []) -> error;
  42. exclude(E, [E|T]) -> {ok, T};
  43. exclude(E, [H|T]) ->
  44. case exclude(E, T) of
  45. error -> error;
  46. {ok, T1} -> {ok, [H|T1]}
  47. end.
  48.  
  49. handle_cast(Request, _State) ->
  50. throw({no_casts, Request}).
  51.  
  52. allocate() ->
  53. gen_server:call(top, allocate).
  54.  
  55. free(Resource) ->
  56. gen_server:call(top, {free, Resource}).
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement