Bug in mnesia:dirty_update_counter

Thomas Johnsson XA (LN/EAB) thomas.xa.johnsson@REDACTED
Thu Mar 10 08:38:32 CET 2005


> I could then replace
>
>  case catch ets:update_counter(Tab, Key, Incr) of
>     {'EXIT',_} -> ets:insert(Tab, {Key, Incr}), Incr;
>     N -> N
>  end

While update_counter is atomic & thread-safe if the key is already in the table,
the above is not thread safe: two or more processes
might simultaneously do the ets:update_counter, get 'EXIT', and insert....

A thread-safe version which takes into account that the key does not exist
previously in the table, should use ets:insert_new (new as of R10 ?) :

case ets:insert_new(Tab, {Key, Incr}) of
   true  -> Incr; %% really was new key, insert succeeded
   false -> ets:update_counter(Tab, Key, Incr)
end

If there's many simultaneous insert_new s, only one will success,
the others perform update_counter.

-- Thomas



More information about the erlang-questions mailing list