[英]multiplatform atomic increment
Until std::atomic
is available, what is the multiplatform (windows & linux) way of atomically increment a variable ?在
std::atomic
可用之前,以原子方式递增变量的多平台(windows 和 linux)方式是什么?
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.我目前正在使用
boost::detail::atomic_count
但它在boost::detail
命名空间中,我不知道它是否可以安全使用。
A multiplatform , but compiler specific way is to use GCC's __sync_fetch_and_add
.多平台但编译器特定的方法是使用 GCC 的
__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
Use InterlockedExchangeAdd instead of InterlockedIncrement - it full analogue, with __sync_fetch_and_add ;使用InterlockedExchangeAdd而不是InterlockedIncrement - 它完全模拟,带有__sync_fetch_and_add ;
#ifdef __GNUC__
#define atomic_inc(ptr) __sync_fetch_and_add ((ptr), 1)
#elif defined (_WIN32)
#define atomic_inc(ptr) InterlockedExchangeAdd ((ptr), 1)
#else
#error "Need some more porting work here"
#endif
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.