Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Share ETS table with two processes?

Tags:

erlang

ets

I create ETS table in one process and I want use it in another process. How I "open" ETS table in second process? Could not find good function in man pages.

like image 481
Lethi Avatar asked Oct 28 '12 20:10

Lethi


2 Answers

you have to create ets table with 'named_table' and 'public' options.

like

T = ets:new(yourtablename,[public,named_table]).

in that case other local processes can use this table by name 'yourtablename'. It's not necessary to explicitly open this table in other processes.

like image 89
Odobenus Rosmarus Avatar answered Sep 27 '22 21:09

Odobenus Rosmarus


If you don't want your table to have a unique name, you can omit named_table and just use public. Then ets:new will return an integer that you need to pass to the process that needs to access the table:

-module(foo).
-compile(export_all).

create_the_table(Pid) ->
    Table = ets:new(mytable, [public]),
    ets:insert(Table, {foo, bar}),
    Pid ! {the_table_is, Table},
    timer:sleep(infinity).

use_the_table() ->
    receive {the_table_is, Table} -> ok end,
    io:format("~p~n", [ets:lookup(Table, foo)]).

Try it from the shell:

2> c(foo).
{ok,foo}
3> Pid1 = spawn(foo, use_the_table, []).
<0.43.0>
4> spawn(foo, create_the_table, [Pid1]).
[{foo,bar}]
<0.45.0>
like image 42
legoscia Avatar answered Sep 27 '22 20:09

legoscia