std::atomic
定义于头文件
template< class T >
struct atomic; (1) (since C++11)
template < class U >
struct atomic<U*>; (2) (since C++11)
每个实例化和 std::atomic
模板的完全实例化定义了 atomic 类型。如果一条线程在另一条线程读时去写一个 atomic 对象,其行为是明确定义的(见数据竞争(data races)的内存模型)。
另外,automic 对象的访问可能建立线程间的同步,并按照std::memory_order
指定的顺序对 non-atomic 的内存访问进行排序。
std::atomic
不能拷贝,也不能移动。
Specializations
Primary template
基本的 std::automic
模板能被任意 TriviallyCopyable 的类型 T 实例化,T 满足 CopyConstructible 和 CopyAssignable。如果下述任何值为 false,则程序是异构的:
std::is_trivially_copyable<T>::value
std::is_copy_constructible<T>::value
std::is_move_constructible<T>::value
std::is_copy_assignable<T>::value
std::is_move_assignable<T>::value
struct Counters { int a; int b}; // user-defined trivially-copyable type
std::atomic<Counters> cnt; // specialization for the user-defined type
std::atomic 使用基本模板。保证其为标准布局结构体。
Member functions
(constructor)
operator=
T operator=( T desired ) noexcept
T operator=( T desired ) volatile noexcept; (1) (since C++11)
atomic& operator(const atomic& ) = delete;
atomic& operator( const atomic& ) volatile = delete; (2) (since C++11)
(1) 原子的使用值 desired 对 atomic 变量进行赋值。等价于 store(desired)
。
(2) atomic 变量不是 CopyAssignable
。
Parameters
desired - value to assign
Return value
desired
Notes
不像大多数的赋值操作符,atomic 类型的赋值操作符不返回left-hand
的参数引用,它返回一个存储值的拷贝。