Skip to content

Instantly share code, notes, and snippets.

@yanmhlv
Created April 25, 2018 13:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yanmhlv/c73e6667d515c341f78776f79604d6d0 to your computer and use it in GitHub Desktop.
Save yanmhlv/c73e6667d515c341f78776f79604d6d0 to your computer and use it in GitHub Desktop.
-module(gs1).
-export([start/0, loop/1]).
% simple gen server with state
start() ->
% io:format("Start ~p~n", [self()]),
% spawn(fun loop/0).
InitialState = [],
spawn(?MODULE, loop, [InitialState]).
loop(State) ->
% io:format("~p enters loop ~n", [self()]),
% receive
% stop -> io:format("~p stops now ~n", [self()]);
% Msg -> io:format("~p receive ~p~n", [self(), Msg]),
% loop()
% end.
receive
{add, Item} -> io:format("~p adds ~p its state~n", [self(), Item]),
NewState = [Item | State],
loop(NewState);
{remove, Item} -> NewState = case lists:member(Item, State) of
true -> lists:delete(Item, State);
false -> io:format("I have no ~p~n)", [Item]),
State
end
loop(NewState);
show_items -> io:format("my items is ~p~n", [State]),
loop(State);
stop -> io:format("~p stops now ~n", [self()]);
_Any -> loop(State)
end.
-module(gs3).
-export([start/0, loop/1]).
% simple gen server with hot code reload
start() ->
InitialState = [],
spawn(?MODULE, loop, [InitialState]).
loop(State) ->
receive
{add, Item} -> io:format("~p adds ~p to its state ~n", [self(), Item]),
NewState = [Item|State],
?MODULE:loop(NewState);
{remove, Item} -> NewState = case lists:member(Item, State) of
true -> lists:delete(Item, State);
false -> io:format("I have no ~p~n)", [Item]),
State
end
?MODULE:loop(NewState);
show_items -> op:format("My items is ~p ~n", [State]),
?MODULE:loop(State);
stop -> io:format("~p stops now ~n", [self()]);
_Any -> ?MODULE:loop(State)
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment