Unable to use Erlang/ets in receive block

2019-06-24 22:00发布

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?

标签: erlang
1条回答
够拽才男人
2楼-- · 2019-06-24 22:27

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

查看更多
登录 后发表回答