a = a + 12;
那么是整个操作(说add_twelve_to(int))的原子?或者是对变量原子(所以operator =())所做的更改?
解决方法
Objects of atomic types are the only C++ objects that are free from data races; that is,if one thread writes to an atomic object while another thread reads from it,the behavior is well-defined.
In addition,accesses to atomic objects may establish inter-thread synchronization and order non-atomic memory accesses as specified by
std::memory_order
.
的std ::原子<>在11 C之前,必须使用(例如)interlocked functions与MSVC或atomic bultins在GCC的情况下执行操作.
另外,std :: atomic<通过允许指定同步和排序约束的各种memory orders,为您提供更多的控制.如果您想了解更多关于C 11原子和内存模型,这些链接可能是有用的:
> C++ atomics and memory ordering
> Comparison: Lockless programming with atomics in C++ 11 vs. mutex and RW-locks
> C++11 introduced a standardized memory model. What does it mean? And how is it going to affect C++ programming?
> Concurrency in C++11
请注意,对于典型的用例,您可能会使用overloaded arithmetic operators或another set of them:
std::atomic<long> value(0); value++; //This is an atomic op value += 5; //And so is this
这些操作将使用std::memory_order_seq_cst
执行,因为它是C 11中所有原子操作的默认顺序.它保证所有原子操作之间的顺序一致性(总全局排序).
然而,在某些情况下,这可能不是必需的(并且没有任何可用的),因此您可能需要使用更明确的形式:
std::atomic<long> value(0); value.fetch_add(1,std::memory_order_relaxed); //Atomic,but there are no synchronization or ordering constraints value.fetch_add(5,std::memory_order_release); //Atomic,performs 'release' operation; guarantees,that no memory accesses in the current thread can be reordered after this store
现在,你的例子:
a = a + 12;
将不会对单个原子op进行评估:它将导致a.load()(它是原子本身),然后在该值与12之间加上最后结果的a.store()(也是原子).
但是,如果你写一个= 12,它将是一个原子操作(如前所述).
至于你的评论:
A regular
int
has atomic loads and stores. Whats the point of wrapping it withatomic<>
您的陈述只适用于x86.还有其他架构,不提供这样的保证.的std ::原子<>是一些东西,这是保证在每一个平台上都是原子的.