Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CompareAndStore would be nice #18

Closed
lkarlslund opened this issue Oct 22, 2022 · 6 comments
Closed

CompareAndStore would be nice #18

lkarlslund opened this issue Oct 22, 2022 · 6 comments

Comments

@lkarlslund
Copy link
Contributor

For concurrent programs a compare and swap value would be really neat, as you might have a race if multiple threads are doing:

value, _ := map.Load(key)
value.Modify()
map.Store(key, value)

The pattern could be changed to

for {
  oldvalue, _ := map.Load(key)
  newvalue := oldvalue
  newvalue.Modify()
  success := map.CompareAndStore(key, oldvalue, newvalue)
  if success {
    break
  }
}
@alphadose
Copy link
Owner

Yes this is useful, will add it in the next release 👍

@lkarlslund
Copy link
Contributor Author

Also variants like LoadOrCalculate would be pretty awesome (same behaviour as LoadOrStore, but you give it a function that returns the value to store, for complex or costly generators of values). The xsync module (https://github.com/puzpuzpuz/xsync) has those, if you need some inspiration.
But really great job on this module so far!

@alphadose
Copy link
Owner

@lkarlslund

Also variants like LoadOrCalculate would be pretty awesome (same behaviour as LoadOrStore, but you give it a function that returns the value to store, for complex or costly generators of values).

This is similar to #16

@bagualing
Copy link

Could you also consider adding two atomic APIs: Swap and CompareAndSwap?

func (m *Map[K, V]) Swap(key K, newValue V) (oldValue V){}
func (m *Map[K, V]) CompareAndSwap(Key K, oldValue, newValue V) (swapped bool){}

I have encountered this requirement in my usage scenario, so, I think it's mybee useful too.

@alphadose
Copy link
Owner

alphadose commented Oct 30, 2022

@bagualing CompareAndSwap is the same as CompareAndStore described by @lkarlslund above
I have taken note of Swap API and shall add it as well

@alphadose
Copy link
Owner

@lkarlslund @bagualing both CompareAndSwap and Swap have been added with 5f15ec7

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants