Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiplatform atomic increment

Until std::atomic is available, what is the multiplatform (windows & linux) way of atomically increment a variable ?

I am currently use boost::detail::atomic_count but it's in boost::detail namespace and I don't know if it's safe to use.

like image 725
cprogrammer Avatar asked Apr 27 '26 19:04

cprogrammer


1 Answers

A multiplatform, but compiler specific way is to use GCC's __sync_fetch_and_add.

Or define such a function yourself with a bit of conditional compilation:

#ifdef __GNUC__
#define atomic_inc(ptr) __sync_fetch_and_add ((ptr), 1)
#elif defined (_WIN32)
#define atomic_inc(ptr) InterlockedIncrement ((ptr))
#else
#error "Need some more porting work here"
#endif
like image 138
chill Avatar answered Apr 30 '26 09:04

chill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!