Re: ETS: update list value without race condition

"Tristan Sloughter" <[email protected]>
Newsgroups gmane.comp.lang.erlang.general
Message-ID <[email protected]>
If you just want to add a single element you can use `select_replace` like in the example in the docs https://erlang.org/doc/man/ets.html#select_replace-2 since a matchspec can include a cons:

MS = ets:fun2ms(fun({K, L}) when is_list(L) -> {K, [marker | L]} end).

A bag might still be more appropriate, but if the goal is to just have a single call that handles this for you then `select_replace` can work. The third option would be a compare and swap with `select_replace`, which is the second example in the docs.

On Thu, Apr 22, 2021, at 05:32, Frank Muller wrote:
> Hi guys
> 
> I’ve a little issue I’m unable to solve with the current ETS API.
> 
> My table is of type set. Keys are integers and values are list of names:
> 123 -> [ jane, john, bob ]
> 456 -> [ joe, alice ]
> …
> 
> Process A with Key=123 wants to delete ‘Jane’ while process B with Key=123 wants to add ‘Adam’.
> 
> First, they both needs to read the value associated with Key=123, update that list accordingly and set back the new value.
> 
> But this lead to race condition (ex. process B could put back ‘jane’ - last write wins).
> 
> Could this problem be solved atomically without involving explicit locking per Key?
> 
> Is there any other better way to represent this data set which will not suffer from the race condition?
> 
> Thanks
> /Frank
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.