Unable to use Erlang / ets in receive block

I am trying to use Erlang / ets to store / update various information by matching the resulting patterns. 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 the cycle number, [f, c] is the central flag, [b] is the ball, and Fcd, Fca, Bd, Ba are the directions and angle of the flag and the ball from the player.

The sender sends this data. Here the pattern matching works correctly , which I checked by printing the values ​​A, Fcd, Fca..etc. I believe something is wrong with Erlang / ets.

When I run this code, I get an error similar to this

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

Can someone tell me what is wrong with this code and how to fix this problem?

+4
source share
1 answer

The problem is that the owner of the ets table is the process that executes the start/1 function, and the default behavior for ets allows the owner to write other processes to read , as it is protected. Two solutions:

  • Create the ets table as public

     S = ets:new(test,[public]). 
  • Set owner for newly created process

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

Documentation for give_away / 3

+7
source

Source: https://habr.com/ru/post/1345412/


All Articles