BAR
BAR

Reputation: 17121

Erlang - Global Variables .. yes I know, I know

Ok I have been trying every which way to figure this out.

I need to get this table to be a global.. I have realized it is much less efficient to pass TableID around.. in the scope of my program.

So I tried creating a new table then looking it up:

TableID = ets:new(tb, [set,public]),
put({tableUniqueID}, TableID),

Then I used:

get({tableUniqueID})

And in the same function it returns TableID just fine... yet when I use it in another function, it returns an undefined.

What?? I thought get and put made a key global..

ALSO before all this I realized you "could" call a table lookup function as such:

ets:lookup(get({tableUniqueID}), msgIn)

Same thing, in function works, outside does not.. Get Put problem..

Then I realized another way to Lookup a table would be by calling the atom of the table

ets:lookup(tb, msgIn)

But this NEVER works, not inside the function, not out..

So my main priority would be to figure why looking up a table by its atom, is not possible. But it says it is most everywhere, including the manual.

The get/put I could live without, As long as I can store table, then lookup the table by its atom identifier.

Can anyone shed light on this dilemma?

Upvotes: 6

Views: 5525

Answers (3)

Dominic
Dominic

Reputation: 806

Since Erlang 21.2 there is a new read optimized version of implementing "globals". Have a look into the module persistent_term

persistent_term:put(Key, Value)

This works great for global flags that are written only once e.g. just on startup but read many time in different processes. All processes have fast read access to these globals:

Value = persistent_term:get(Key)

Upvotes: 0

Daniel Luna
Daniel Luna

Reputation: 1979

The correct answer to your problem is to not use a global table at all, but to rather pass around the information. Especially since you mention efficiency in your original question. You are creating a congestion point in your code which will make it have worse performance on any multi core machine.

The ets table is implemented as a process that all other processes have to call to get a value.

Upvotes: 5

BAR
BAR

Reputation: 17121

I GOT IT!!

Wish the docs, would say this under the lookup function.. Better yet, everyone who writes tutorials on ets, or more so books

The solution is to

TableID = ets:new(tb, [set,public,named_table])

That named_table is the important part

Some digging through man pages, but

;)

Upvotes: 6

Related Questions