C ++ std :: atomic与Boost原子 [英] C++ std::atomic vs. Boost atomic
问题描述
在我的应用程序中,我有一个int和一个bool变量,被多个线程访问(多个写/读)。目前,我使用两个互斥体,一个为int,一个为bool保护这些变量。
In my application, I have an int and a bool variable, which are accessed (multiple write/read) by multiple threads. Currently, I am using two mutexes, one for int and one for bool to protect those variables.
我听说过使用原子变量和操作符来写锁,线程程序。我的问题是
I heard about using atomic variables and operators to write lock-free multi-thread program. My questions are
- 原子变量和运算符的定义是什么?
- std :: atomic 和
boost / atomic.hpp ?哪一个更标准或更流行? - 这些库是平台相关的吗?我现在使用gnu gcc 4.6 on
Linux,但理想情况下它应该是跨平台的。我听说原子的定义实际上还取决于硬件。任何人都可以解释一下吗? - 在多个线程之间共享bool变量的最好方法是什么?我不想使用 volatile 关键字。
- What's the definition of atomic variables and operators?
- What's the main difference between std::atomic and boost/atomic.hpp? Which one is more standard or popular?
- Are these libraries platform-dependent? I am using gnu gcc 4.6 on Linux at the moment, but ideally it shall be cross-platform. I heard that the definition of "atomic" actually depends on the hardware as well. Can anyone explain that as well?
- What's the best way to share a bool variable among multiple threads? I would prefer not to use the "volatile" keyword.
这些代码是否线程安全? / p>
Are these code thread-safe?
double double_m; // double_m is only accessed by current thread.
std::atomic<bool> atomic_bool_x;
atomic_bool_x = true && (double_m > 12.5);
int int_n; // int_n is only accessed by current thread.
std::atomic<int> atomic_int_x;
std::atomic<int> atomic_int_y;
atomic_int_y = atomic_int_x * int_n;
推荐答案
我不是专家或任何东西,我知道:
I'm not an expert or anything, but here's what I know:
-
std :: atomic
$ c> load 和store
(以及一些其他操作)是明确定义的。 - 我假设
std :: atomic
是基于boost :: atomic
。如果可以,使用std
,否则使用boost
。 - 两个可移植的,
std
完全是这样,但是你的编译器将需要支持C ++ 11 - 可能
std :: atomic_bool
。您不应该使用volatile。
std::atomic
simply says that callingload
andstore
(and a few other operations) concurrently is well-defined. An atomic operation is indivisible - nothing can happen 'in-between'.- I assume
std::atomic
is based off ofboost::atomic
. If you can, usestd
, otherwise useboost
. - They are both portable, with the
std
being completely so, however your compiler will need to support C++11 - Likely
std::atomic_bool
. You should not need to use volatile.
此外,我相信 load
store
不同于 operator =
/ operator T
只有。加载 /
存储是原子
Also, I believe load
/store
differs from operator=
/operator T
only .load
/store
are atomic
不要迷茫。我检查了标准,看起来操作符是以 load
/ store
/ etc定义的,但是他们可能返回不同的东西。
Nevermind. I checked the standard and it appears that the operators are defined in terms of load
/store
/etc, however they may return different things.
进一步阅读:
- http://en.cppreference.com/w/cpp/atomic/atomic
- C ++ 11标准
- C ++并行操作
这篇关于C ++ std :: atomic与Boost原子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!