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.
4 Answers
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>
As Odobenus and legoscia said, you can access an ets table by name (make it named_table) or by identifier (pass the identifier to other process), and make the table public.
Whether it's accessed from another module makes no difference.
Make sure that when ets:info is executed, the table is already created (by the other process).
new(Name, Options) -> tid() | atom()
in here
Creates a new table and returns a table identifier which can be used in subsequent operations. The table identifier can be sent to other processes so that a table can be shared between different processes within a node.
public Any process may read or write to the table.
protected The owner process can read and write to the table. Other processes can only read the table. This is the default setting for the access rights.
private Only the owner process can read or write to the table.