Share ETS table with two processes?
Asked Answered
K

4

5

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.

Kero answered 28/10, 2012 at 20:6 Comment(1)
Not posting this as an answer because I have no experience with ETS, but as long as all processes are on the same VM, you should be able to simply refer to the correct table name (atom) in any ETS function call. See: learnyousomeerlang.com/etsSelfoperating
W
12

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.

Wiencke answered 28/10, 2012 at 21:2 Comment(2)
and my can access this from different modules? I doing ets:info(mytab,size) and in one module size is 1 but in other module size is undefined. Table names are exact and my declared as you sayKero
To add, i using atom names: Tab = ets:new(mytab,[named_table,public,set]). so when i do info() in last comment i use mytab to call table sizeKero
O
4

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>
Oni answered 29/10, 2012 at 18:6 Comment(0)
T
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).

Tropaeolin answered 26/1, 2014 at 10:21 Comment(0)
M
0

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.

Musgrave answered 24/2, 2014 at 5:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.