Skip to content

Instantly share code, notes, and snippets.

@ndpar
Created December 12, 2010 20:36
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 ndpar/738305 to your computer and use it in GitHub Desktop.
Save ndpar/738305 to your computer and use it in GitHub Desktop.
-module(generic_server).
-export([start/0, loop/2]).
-export([request/1, change_state/1, change_function/1]).
%% Server
start() ->
register(?MODULE, spawn(?MODULE, loop, [2, fun erlang:'+'/2])).
loop(State, Function) ->
receive
{new_state, S} -> loop(S, Function);
{new_fun, F} -> loop(State, F);
{request, From, Request} ->
From ! {response, apply(Function, [State, Request])},
loop(State, Function)
end.
%% Client
change_state(NewState) ->
?MODULE ! {new_state, NewState},
ok.
change_function(NewFunction) ->
?MODULE ! {new_fun, NewFunction},
ok.
request(Request) ->
?MODULE ! {request, self(), Request},
receive
{response, Result} -> Result
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment