Skip to content

Instantly share code, notes, and snippets.

@derdesign
Created October 31, 2012 02:18
Show Gist options
  • Save derdesign/3984424 to your computer and use it in GitHub Desktop.
Save derdesign/3984424 to your computer and use it in GitHub Desktop.
dict_server
-module(dict_server).
-export([start/0, stop/0, stop/1, get/1, get/2, set/1, set/2]).
-vsn("1.0").
start() ->
register(?MODULE, self()),
Table = ets:new(?MODULE, []),
io:format("Initializing Dictionary Server...~n", []),
loop(Table).
stop() ->
?MODULE ! quit.
stop(Node) ->
{?MODULE, Node} ! quit,
ok.
loop(Table) ->
receive
{get, Key} ->
Reply = ets:lookup(Table, Key),
io:format("~p~n", [Reply]),
loop(Table);
{get, Key, From} ->
Reply = ets:lookup(Table, Key),
From ! {reply, Reply},
loop(Table);
{set, Data} ->
Reply = ets:insert(Table, Data),
io:format("~p~n", [Reply]),
loop(Table);
{set, Data, From} ->
Reply = ets:insert(Table, Data),
From ! {reply, Reply},
loop(Table);
quit ->
io:format("Stopping Dictionary Server... Bye!~n", []);
abort ->
io:format("Aborting Dictionary Server. Shutting Down...~n", []),
init:stop();
_Other ->
loop(Table)
end.
call(Pid, Action, Data) ->
Message = {Action, Data, self()},
if
is_pid(Pid) ->
Pid ! Message;
true ->
{?MODULE, Pid} ! Message
end,
receive
{reply, Reply} ->
Reply
after 60000 ->
timeout
end.
get(Key) ->
call(?MODULE, get, Key).
get(Node, Key) ->
call(Node, get, Key).
set(Data) ->
true = call(?MODULE, set, Data),
ok.
set(Node, Data) ->
true = call(Node, set, Data),
ok.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment