Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to use Erlang/ets in receive block

Tags:

erlang

I am trying to use Erlang/ets to store/update various informations by pattern matching received data. Here is the code

start() -> 
    S = ets:new(test,[]),
    register(proc,spawn(fun() -> receive_data(S) end)).

receive_data(S) ->
    receive
        {see,A} -> ets:insert(S,{cycle,A}) ;
        [[f,c],Fcd,Fca,_,_] -> ets:insert(S,{flag_c,Fcd,Fca});
        [[b],Bd,Ba,_,_] -> ets:insert(S,{ball,Bd,Ba})



    end,
    receive_data(S).

Here A is cycle number, [f,c] is center flag , [b] is ball and Fcd,Fca, Bd, Ba are directions and angle of flag and ball from player.

Sender process is sending these informations. Here, pattern matching is working correctly which I checked by printing values of A, Fcd,Fca..etc. I believe there is something wrong with the use of Erlang/ets.

When I run this code I get error like this

Error in process <0.48.0> with exit value: {badarg,[{ets,insert,[16400,{cycle,7}]},{single,receive_data,1}]

Can anybody tell me what's wrong with this code and how to correct this problem?

like image 607
Dinesh Avatar asked Mar 27 '11 11:03

Dinesh


1 Answers

The problem is that the owner of the ets-table is the process running the start/1 function and the default behavior for ets is to only allow the owner to write and other processes to read, aka protected. Two solutions:

  1. Create the ets table as public

    S = ets:new(test,[public]). 
    
  2. Set the owner to your newly created process

    Pid = spawn(fun() -> receive_data(S) end, 
    ets:give_away(test, Pid, gift)
    register(proc,Pid)
    

Documentation for give_away/3

like image 165
D.Nibon Avatar answered Oct 13 '22 01:10

D.Nibon