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
  • 71,616
  • 66
  • 178
  • 288
  • 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
  • 116,304
  • 97
  • 251
  • 314
Anton Tykhyy
  • 18,937
  • 5
  • 53
  • 54
3

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

BCS
  • 71,616
  • 66
  • 178
  • 288
Test
  • 1,673
  • 1
  • 11
  • 10