多平台原子增量

发布于 2024-12-13 14:04:25 字数 183 浏览 5 评论 0原文

std::atomic 可用之前,多平台(Windows 和 Linux)原子地递增变量的方法是什么?

我目前正在使用 boost::detail::atomic_count 但它位于 boost::detail 命名空间中,我不知道它是否可以安全使用。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

伤痕我心 2024-12-20 14:04:25

一种多平台但编译器特定的方法是使用 GCC 的 __sync_fetch_and_add

或者通过一些条件编译自己定义这样的函数:

#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

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
森末i 2024-12-20 14:04:25

使用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

您可以找到经过验证的 msvc/gcc 调用类似 此处 (x86)

Use InterlockedExchangeAdd instead of InterlockedIncrement - it full analogue, with __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

You can find proven analogs of msvc/gcc calls here (x86)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文