[英]Thread-safe, lock-free increment function?
更新:在 C 或 C++ 中可用的所有 Linux 发行版上是否有线程安全、无锁和可用的增量函数?
GLib has functions to do this. GLib 具有执行此操作的功能。 You might check out
你可能会检查 http://library.gnome.org/devel/glib/stable/glib-Atomic-Operations.html
http://library.gnome.org/devel/glib/stable/glib-Atomic-Operations.html
Specifically, it sounds like you want g_atomic_int_inc()具体来说,听起来你想要 g_atomic_int_inc()
I think these are GNU extensions, and processor specific, but have a look at GNU C Atomic Builtins .我认为这些是 GNU 扩展和特定于处理器的,但请查看GNU C Atomic Builtins 。
I think there are also atomic "libraries" available that use inline assembly etc. to provide such features.我认为还有可用的原子“库”使用内联汇编等来提供此类功能。
The current C and C++ standards don't define such a thing.当前的 C 和 C++ 标准没有定义这样的东西。 Your implementation may well have one.
您的实现很可能有一个。
12 years have passed since the other answers and it is now in the standard and it is possible to do this since C++11 using the atomic operations library .自从其他答案以来已经过去了 12 年,现在它已成为标准,并且从 C++11 开始使用 原子操作库就可以做到这一点。
#include <iostream>
#include <atomic>
int main() {
std::atomic<int> atomic_i{5};
std::cout << atomic_i.is_lock_free() << std::endl; // 1, which means lock free
atomic_i++;
std::cout << atomic_i << std::endl; // 6
return 0;
}
If you want a normal, non-atomic integer that you want to increment in atomic operations only sometimes, you can do this:如果你想要一个普通的、非原子的整数,你只想在原子操作中递增,你可以这样做:
int j = 8;
j = ++std::atomic<int>(j);
std::cout << j << std::endl; // 9
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.