4

I have found lock inc addr but that doesn't keep a copy of the stored value around and even a read immediately after it in the same thread could come after a competing write.

The best solution I have found is a load/inc/cas loop.

BCS
  • 75,627
  • 68
  • 187
  • 294
  • In C++11 std::atomic, [`fetch_add`](http://en.cppreference.com/w/cpp/atomic/atomic/fetch_add) `+ 1` does what you want. Or more simply, [`operator++`](http://en.cppreference.com/w/cpp/atomic/atomic/operator_arith), but then you can't use a weaker `memory_order_relaxed` to make it faster on non-x86 if you don't need a barrier. (`lock xadd` implements `fetch_add`, returning the old value). – Peter Cordes Sep 02 '17 at 08:16
  • [Can num++ be atomic for 'int num'?](https://stackoverflow.com/q/39393850/995714) – phuclv Jan 14 '18 at 08:37

2 Answers2

11

lock xadd is your friend.

Nathan Fellman
  • 122,701
  • 101
  • 260
  • 319
Anton Tykhyy
  • 19,370
  • 5
  • 54
  • 56
3

see atomic_impl.h for more x86/x86_64 atomic primitives and usage.

BCS
  • 75,627
  • 68
  • 187
  • 294
Test
  • 1,697
  • 1
  • 11
  • 10