1

I'm trying to implement a process that I can query/update for some state information (I'm working on an SMS service and want to store some local data based on responses - later I will use a DB but for now I want to use ETS, this is my first Erlang project so I think it's useful to learn). Unfortunately it seems like my inserts are not coming through and I don't understand why. This is the module:

-module(st).
-compile(export_all).

maintain_state() ->
    Tab = ets:new(state, [set]),
    receive
        {Pid, lookup, Key} ->
            Pid ! ets:lookup(Tab, Key),
            maintain_state();
        {Pid, update, Key, Handler} ->
            NewState = Handler(ets:lookup(Tab, Key)),
            Status = ets:insert(Tab, NewState),
            Pid ! {Status, NewState},
            maintain_state();
        {Pid, statelist} ->
            Pid ! ets:tab2list(Tab),
            maintain_state();
        kill ->
            void
    end,
    ets:delete(Tab).

start_state_maintainer() ->
    Pid = spawn(st, maintain_state, []),
    register(state, Pid).

update_state(StateHandler) ->
    state ! {self(), update, testing, StateHandler},
    receive
        After ->
            After
    after 1000 ->
            throw("Timeout in update_state")
    end.

lookup_state() ->
    state ! {self(), lookup, testing},
    receive
        Value ->
            Value
    after 1000 ->
            throw("Timeout in lookup_state")
    end.

all_state() ->
    state ! {self(), statelist},
    receive
        Value ->
            Value
    after 1000 ->
            throw("Timeout in all_state")
    end.

Which I then load in an erl session:

> c(st).
> st:start_state_maintainer().
> st:lookup_state().
[]
> st:update_state(fun (St) -> {testing, myval} end).
{true, {testing, myval}}
> st:all_state().
[]

Since update_state shows true I figured the insert was successful, but nothing seems to be stored in the table. What am I doing wrong?

PS: if this whole approach is flawed or you have other remarks about my code I would appreciate those as well.

1 Answer 1

5

Ok. Let's run your code again.

1> c(st). % compile your code
{ok,st}

% Before doing anything. let's get count of all ETS tables using ets:all/0
2> length(ets:all()). 
16 % So the Erlang VM has 16 tables after starting it

3> st:start_state_maintainer().
true

% Let's check count of tables again:
4> length(ets:all()).          
17 % Your process has created its own table

5> st:lookup_state().
[]

% Check count of tables again
6> length(ets:all()).
18 % Why????

7> st:update_state(fun (St) -> {testing, myval} end).
{true,{testing,myval}}
8> length(ets:all()).                                
19

9> st:all_state().   
[]
10> length(ets:all()).
20

So in line 5 in function maintain_state/0 you are creating an ETS table and in lines 9, 14 and 17 you are calling this function again ! So after receiving each message (except void) you are creating new ETS table!
Let's see those tables:

11> P = whereis(state). % Get process id of 'state' and assign it to P
<0.66.0>
12> Foreach = 
fun(Tab) -> 
    case ets:info(Tab, owner) of 
        P -> % If owner of table is state's pid
            io:format("Table ~p with data ~p~n"
                      ,[Tab, ets:tab2list(Tab)]); 
        _ -> 
            ok
    end 
end.
#Fun<erl_eval.6.118419387>

13> lists:foreach(Foreach, ets:all()).
Table 28691 with data []
Table 24594 with data []
Table 20497 with data [{testing,myval}]
Table 16400 with data []
ok

And after killing your process, We should have 16 tables again:

14> exit(P, kill).
true
15> length(ets:all()).                                                                                                                      
16

You have two choises. You can use named tables like this:

maintain_state() ->
    % With 'named_table' option, we can use the name of table in code:
    Tab = ets:new(state, [set, named_table]),
    maintain_state2().

maintain_state2() ->
    receive
        {Pid, lookup, Key} ->
            Pid ! ets:lookup(state, Key), % I used name of table
            maintain_state2();
...

Or use table as argument of maintain_state2:

maintain_state() ->
    Tab = ets:new(state, [set]),
    maintain_state2(Tab).

maintain_state2(Tab) ->
    receive
        {Pid, lookup, Key} ->
            Pid ! ets:lookup(Tab, Key),
            maintain_state2(Tab);
...

I changed the code to one of above examples and here is the result:

1> st:start_state_maintainer().
true
2> st:lookup_state().
[]
3> st:update_state(fun (St) -> {testing, myval} end).
{true,{testing,myval}}
4> st:all_state().
[{testing,myval}]
5> length(ets:all()).
17

After playing with Erlang's message passing and understanding its functionality and its concepts, I really suggest you to learn OTP design principles and OTP behaviors like gen_server and use them instead of writing your own receive ... and Pid ! ... statements.

1
  • Ah I see, I should have been able to catch that error :) I thought maybe there was some system for transactions that I didn't know about and that I needed to commit my inserts or so. Thanks for the advice about OTP, I will definitely look into that. Aug 28, 2018 at 10:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.