[erlang-questions] Shared ETS Access

L. S. lsearchw@REDACTED
Mon Jan 11 07:27:46 CET 2010


Thanks! This is the type of clarification I needed.
I was thinking of a situation where there is no clear parent-child
relationship. I am experimenting with a Yaws appmod setup where each
request reads a token from an ETS table (strictly from memory, for
speed).

On 1/10/10, Steve Vinoski <vinoski@REDACTED> wrote:
> On Sun, Jan 10, 2010 at 4: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, coffee}).
>>
>>
>> ... (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.
>>
>>    %ErlShellProcess2:
>>        ?
>>
>
> -module(ets_ex).
> -export([run/0]).
>
> run() ->
>     Parent = self(),
>     spawn(fun() ->
>                   TblName = my_table,
>                   Tbl = ets:new(TblName, [public, named_table]),
>                   Parent ! {ready, self(), TblName},
>                   receive
>                       stop ->
>                           ets:delete(Tbl)
>                   end
>           end),
>     receive
>         {ready, Loop, TblNm} ->
>             ets:insert(TblNm, {"key", "value"}),
>             Lookup = ets:lookup(TblNm, "key"),
>             io:format("lookup returned ~p~n", [Lookup]),
>             Loop ! stop
>     end.
>
> The spawned anonymous function creates and owns the ets table, and for this
> example serves essentially the same purpose as a gen_server and its receive
> loop would. The run() function spawns the loop, waits for the message
> telling it the table name, then does an insert and a lookup on the table.
> Note that all the main part of the run() function knows is the name of the
> table received in the message from the loop.
>
> --steve
>


More information about the erlang-questions mailing list