简体   繁体   English

多平台原子增量

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM