[erlang-questions] Shared ETS Access

Colm Dougan colm.dougan@REDACTED
Mon Jan 11 00:18:24 CET 2010


On Sun, Jan 10, 2010 at 9:57 PM, L. S. <lsearchw@REDACTED> wrote:
> Where can I find a full, simple example of one Erlang process creating an
> ETS table and having another process access that table?
>
> After looking at the docs, I seem to understand the basic call to create and
> populate a table...
>
>    %ErlShellProcess1:
>        TabId = ets:new(food, [public, named_table]).
>        ets:insert(TabId, {drink, cofee}).
>
>
> ... (And I know I may have to use gen_server to create a persistent process)
> but I don't know the mechanics to make the it work.

Here is a basic example of a key/value store :

##########

-module(my_keystore).
-behaviour(gen_server).

-export([start_link/0]).
-export([get/1, put/2]).

%% Internal exports
-export([
    init/1, handle_call/3,
    %handle_cast/2, handle_info/2,
    code_change/3, terminate/2
]).

%% Public
start_link() ->
    gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).

get(Key) ->
    case ets:lookup(?MODULE, Key) of
        [] ->
            undefined;
        [{_Key, Value}] ->
            Value
    end.

put(Key, Value) ->
    gen_server:call(?MODULE, {put, Key, Value}).

%% context
-record(state, {
    tab
}).

%% gen_server callbacks
init(_Args) ->
    Tab = ets:new(?MODULE, [named_table, public, set]),
    io:format("Initing ...~n"),
    {ok, #state{tab = Tab}}.

handle_call({put, Key, Value}, _From,  State) ->
    ets:insert(?MODULE, {Key, Value}),
    {reply, ok, State}.

terminate(Reason, _State) ->
    io:format("~p is terminating [~p]", [?MODULE, Reason]),
    ok.

code_change(_OldVsn, State, _Extra) ->
    {ok, State}.


##########

(You will get warnings about undefined callbacks with this, but I left
those out for brevity).

You will notice that the 'get' function uses the fact that the ets
table is 'public' and queries it directly in the context of the
calling process, and without calling into the gen_server process which
created the table.  (If the ets table were private then the get
function would have to be implemented in the same way as the 'put'
function i.e. by "calling into" the process encapsulating the
gen_server).

HTH,
Colm


More information about the erlang-questions mailing list