1

I am learning lock-free structure, and I noticed an ABA problem.

I think Java's AtomicStampedReference can solve this problem.

So, is there anything similar in C++ that can solve this?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
nick huang
  • 443
  • 4
  • 12

2 Answers2

2

There isn't a direct equivalent. You could implement it yourself, the source for AtomicStampedReference is here: https://github.com/JetBrains/jdk8u_jdk/blob/master/src/share/classes/java/util/concurrent/atomic/AtomicStampedReference.java

You could probably implement this in c++ maybe making use of std::atomic<std::shared_ptr> to implement the private volatile Pair<V> pair.

If you don't need the full functionality of AtomicStampedReference you can probably use std::atomic<std::shared_ptr> directly in your code. If you don't have c++20 then you can use the previous stand-alone atomic shared_ptr functions

Alan Birtles
  • 32,622
  • 4
  • 31
  • 60
  • The problem with the C++11 `std::atomic_...` functions is that they're not lock-free in any implementations, AFAIK. – Eric Dec 12 '19 at 14:14
0

Maybe you should look at std::atomic. I have never heard of "AtomicStampedReference", but from just a cursory look, it seems to be an atomic reference. std::atomic is for atomic variables. Hopefully this is what you're looking for.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • got it, I have found i can wrap the struct to atomic. Thank you – nick huang Dec 10 '19 at 10:51
  • @nickhuang note that `std::atomic` will almost certainly use a mutex for when `T` is not one of the built in types – Alan Birtles Dec 10 '19 at 12:02
  • 1
    @AlanBirtles: Some targets support lock-free `atomic` for structs that are 2 pointers wide. Especially 32-bit targets like modern ARMv8, and 32-bit x86. Modern GCC for x86-64 doesn't inline `lock cmpxchg16b` but libatomic will use it instead of a mutex. (But it uses it even for pure loads when you only care about one member. You can hack around that with a union: [How can I implement ABA counter with c++11 CAS?](//stackoverflow.com/a/38991835)). Anyway, in general a struct will be lock-free if its size is a small power of 2, even if it has multiple smaller members. – Peter Cordes Dec 10 '19 at 22:03
  • 1
    A little bit of googling would reveal that AtomicStampedReference is Java's atomic reference + stamp that helps avoid the ABA problem in lock-free programming. – Eric Dec 12 '19 at 13:56