2016-06-21 62 views
1

二郎版本18.3二郎ETS選擇壞ARG

得到了與二郎ETS一個奇怪的錯誤:選擇/ 1

下面的代碼將從表中做選擇元素,並把他們

,如果我做

save(10), %% insert 10 data 

remove(3) %% remove 3 data per time 

它的工作原理

,如果我做

save(6007), %% insert more datas 

remove(400) %% remove 400 data per time 

這是不好的ARG在ets:select(Cont)還,這是將在第一或第二循環,但總是在那裏。

有什麼建議嗎?

-record(item, {name, age}). 
%% start the table 
start() -> 
ets:new(example_table, [public, {keypos, 2}, 
named_table, 
{read_concurrency, true}, 
{write_concurrency, true}]). 

%% insert n demo data 
save(Limit) -> 
All = lists:seq(1 ,Limit), 
All_rec = [#item{name = {<<"demo">>, integer_to_binary(V)} , age = V} || V <- All], 
ets:insert(example_table, All_rec). 

%% remove all data, n data per select 
remove(Limit) -> 
    M_head = #item{name = '$1', _ = '_'}, 
M_guards = [], 
M_result = ['$1'], 
M_spec = [{M_head, M_guards, M_result}], 

case ets:select(example_table, M_spec, Limit) of 
     '$end_of_table' -> 
     0; 
     {Keys, Cont} -> 

     remove(example_table, Keys, Cont, 0, []) 
     end. 

     remove(Table, [], Cont, Count, _Acc) -> 

     case ets:select(Cont) of 
      '$end_of_table' -> 
      Count; 
      {Keys, Cont_1} -> 

      remove(Table, Keys, Cont_1, Count, []) 
     end; 
     remove(Table,[Key | T], Cont, Count, Acc) -> 
     case ets:take(example_table, Key) of 
      [] -> 
     remove(Table, T, Cont, Count, Acc); 
      [Rec] -> 
     io:format("Rec [~p] ~n", [Rec]), 
     remove(Table, T, Cont, Count + 1, [Rec | Acc]) 
     end. 

堆棧跟蹤

 4> example_remove:save(6007). 
     true 
    5> example_remove:remove(500). 
    ** exception error: bad argument 
    in function ets:select/1 
    called as ets:select({example_table,304,500,<<>>, 
          [{<<"demo">>,<<"2826">>}, 
           {<<"demo">>,<<"3837">>}, 
           {<<"demo">>,<<"5120">>}, 
           {<<"demo">>,<<"878">>}, 
           {<<"demo">>,<<"1195">>}, 
           {<<"demo">>,<<"1256">>}, 
           {<<"demo">>,<<"1449">>}, 
           {<<"demo">>,<<"5621">>}, 
           {<<"demo">>,<<"5768">>}], 
          9}) 
in call from example_remove:remove/5 (d:/workspace/simple-cache/src/example_remove.erl, line 47) 
+0

衛士主刪除週期是什麼代碼部分的目的是什麼?另外,告訴我們你得到的錯誤日誌。 –

+0

我無法複製。 – Lol4t0

+0

@ Lol4t0您使用的是哪個版本的erlang? – user3644708

回答

3

我相信這是因爲你同時在桌子上迭代和修改。

我建議包裝與safe_fixtable

remove(Limit) -> 
    ets:safe_fixtable(example_table, true), 
    M_head = #item{name = '$1', _ = '_'}, 
    M_guards = [], 
    M_result = ['$1'], 
    M_spec = [{M_head, M_guards, M_result}], 

    R = case ets:select(example_table, M_spec, Limit) of 
     '$end_of_table' -> 
      0; 
     {Keys, Cont} -> 
      remove(example_table, Keys, Cont, 0, []) 
    end, 
    ets:safe_fixtable(example_table, false), 
    R. 
+0

謝謝。這是有道理的。 – user3644708