c – 什么是std :: atomic?

我了解std :: atomic<>是一个原子对象.但原子在多大程度上?为了我的理解,一个操作可以是原子的.通过使对象原子化究竟是什么意思?例如,如果有两个线程同时执行以下代码
a = a + 12;

那么是整个操作(说add_twelve_to(int))的原子?或者是对变量原子(所以operator =())所做的更改?

解决方法

std::atomic<>的每个实例化和全面专业化表示类型,不同的线程可以同时运行,而不会引起未定义的行为:

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 operatorsanother 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 with atomic<>

您的陈述只适用于x86.还有其他架构,不提供这样的保证.的std ::原子<>是一些东西,这是保证在每一个平台上都是原子的.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...