Search code examples
c++boostsynchronizationatomicmultiplatform

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.


Solution

  • 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