[erlang-questions] Shared ETS Access
Steve Vinoski
vinoski@REDACTED
Sun Jan 10 23:30:30 CET 2010
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, 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.
>
> %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