Unable to use Erlang/ets in receive block

半城伤御伤魂 提交于 2019-12-10 13:45:06

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/5448803/unable-to-use-erlang-ets-in-receive-block

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!