微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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 ::原子<>是一些东西,这是保证在每一个平台上都是原子的.

原文地址:https://www.jb51.cc/c/111295.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐