【问题标题】:Unable to use Erlang/ets in receive block无法在接收块中使用 Erlang/ets
【发布时间】:2011-07-23 20:35:03
【问题描述】:

我正在尝试使用 Erlang/ets 通过模式匹配接收到的数据来存储/更新各种信息。这是代码

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).

这里 A 是循环数,[f,c] 是中心标志,[b] 是球,Fcd,Fca, Bd, Ba 是来自球员的标志和球的方向和角度。

发送者进程正在发送这些信息。在这里,模式匹配工作正常,我通过打印 A、Fcd、Fca..etc 的值进行了检查。我认为使用 Erlang/ets 有问题。

当我运行这段代码时,我得到这样的错误

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

谁能告诉我这段代码有什么问题以及如何解决这个问题?

【问题讨论】:

    标签: erlang


    【解决方案1】:

    问题在于 ets-table 的所有者是运行 start/1 函数的进程,而 ets 的默认行为是 only allow the owner to write and other processes to read,也就是受保护的。两种解决方案:

    1. 将 ets 表创建为公开的

      S = ets:new(test,[public]). 
      
    2. 将所有者设置为您新创建的进程

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

    give_away/3 的文档

    【讨论】:

    • 如何公开erlang函数?
    猜你喜欢
    • 2012-08-07
    • 2013-12-25
    • 2014-11-30
    • 2016-10-27
    • 1970-01-01
    • 2016-06-03
    • 2012-10-14
    • 2011-02-17
    • 2015-07-09
    相关资源
    最近更新 更多