[erlang-questions] Replacing ets tables - renaming and race condition
Paulo Sérgio Almeida
psa@REDACTED
Wed Apr 4 11:11:42 CEST 2007
I want to make some computation periodically, e.g. one a minute, and
store the results into an ets table. To allow other processes to lookup
values any time, before the whole computation is finished (and as the
computation must start from an empty table which gets filled, and can
take some time), I work on a temporary table and then rename it to the
one looked up by other processes. But if I do:
Tab = ets:new(tmp, [named_table]),
compute(Tab),
ets:rename(tmp, used_table)
this causes an exception if used_table already exists. On the other
hand, if I delete the original table:
Tab = ets:new(tmp, [named_table]),
compute(Tab),
ets:delete(used_table),
ets:rename(tmp, used_table)
there is the possible race of someone trying to look it up before the
rename. I assume this pattern must have occurred to someone. How can the
race be avoided?
(Btw, In my case there is no need for "transactions" involving several
lookups in the table same, and no problem if some process does two
consecutive lookups, one in the "old" table and the other in the "new"
table.)
I understand that the rename causes an exception to avoid acidentally
destroying tables. But it would be useful to have a variant that renames
and deletes atomically, if the target exists, maybe with an extra
"force" parameter. e.g.:
ets:rename(from, to, true)
Paulo
More information about the erlang-questions
mailing list