pooled_gs.erl 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. -module(pooled_gs).
  2. -behaviour(gen_server).
  3. -define(SERVER, ?MODULE).
  4. %% ------------------------------------------------------------------
  5. %% API Function Exports
  6. %% ------------------------------------------------------------------
  7. -export([start_link/1,
  8. get_id/1,
  9. ping/1,
  10. ping_count/1,
  11. crash/1,
  12. stop/1
  13. ]).
  14. %% ------------------------------------------------------------------
  15. %% gen_server Function Exports
  16. %% ------------------------------------------------------------------
  17. -export([init/1, handle_call/3, handle_cast/2, handle_info/2,
  18. terminate/2, code_change/3]).
  19. %% ------------------------------------------------------------------
  20. %% API Function Definitions
  21. %% ------------------------------------------------------------------
  22. start_link(Args ={_Type}) ->
  23. % not registered
  24. gen_server:start_link(?MODULE, Args, []).
  25. get_id(S) ->
  26. gen_server:call(S, get_id).
  27. ping(S) ->
  28. gen_server:call(S, ping).
  29. ping_count(S) ->
  30. gen_server:call(S, ping_count).
  31. crash(S) ->
  32. gen_server:cast(S, crash),
  33. sent_crash_request.
  34. stop(S) ->
  35. gen_server:call(S, stop).
  36. %% ------------------------------------------------------------------
  37. %% gen_server Function Definitions
  38. %% ------------------------------------------------------------------
  39. -record(state, {
  40. type = "",
  41. id,
  42. ping_count = 0
  43. }).
  44. init({Type}) ->
  45. {ok, #state{type = Type, id = make_ref()}}.
  46. handle_call(get_id, _From, State) ->
  47. {reply, {State#state.type, State#state.id}, State};
  48. handle_call(ping, _From, #state{ping_count = C } = State) ->
  49. State1 = State#state{ping_count = C + 1},
  50. {reply, pong, State1};
  51. handle_call(ping_count, _From, #state{ping_count = C } = State) ->
  52. {reply, C, State};
  53. handle_call(stop, _From, State) ->
  54. {stop, normal, stop_ok, State};
  55. handle_call(_Request, _From, State) ->
  56. {noreply, ok, State}.
  57. handle_cast(crash, _State) ->
  58. erlang:error({pooled_gs, requested_crash});
  59. handle_cast(_Msg, State) ->
  60. {noreply, State}.
  61. handle_info(_Info, State) ->
  62. {noreply, State}.
  63. terminate(_Reason, _State) ->
  64. ok.
  65. code_change(_OldVsn, State, _Extra) ->
  66. {ok, State}.