c – 什么是std :: atomic?
我了解std :: atomic<>是一个原子对象.但原子在多大程度上?为了我的理解,一个操作可以是原子的.通过使对象原子化究竟是什么意思?例如,如果有两个线程同时执行以下代码
a = a + 12; 那么是整个操作(说add_twelve_to(int))的原子?或者是对变量原子(所以operator =())所做的更改? 解决方法
std::atomic<>的每个实例化和全面专业化表示类型,不同的线程可以同时运行,而不会引起未定义的行为:
的std ::原子<>在11 C之前,必须使用(例如)interlocked functions与MSVC或atomic bultins在GCC的情况下执行操作. 另外,std :: atomic<通过允许指定同步和排序约束的各种memory orders,为您提供更多的控制.如果您想了解更多关于C 11原子和内存模型,这些链接可能是有用的: > C++ atomics and memory ordering 请注意,对于典型的用例,您可能会使用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::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,它将是一个原子操作(如前所述). 至于你的评论:
您的陈述只适用于x86.还有其他架构,不提供这样的保证.的std ::原子<>是一些东西,这是保证在每一个平台上都是原子的. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |