atomic是在多线程编程中经常使用的一个类。使用的时候需要包含
atomic内部封装一个值,并保证对该值的访问的互斥性。可以用来进行线程同步。使用非常方便。说白了就是atomic内部保存的值是线程安全的,不用担心多线程访问时的同步问题。也就是说保证对内部值的读取和保存的操作的原子性。
atomic是个模板类,可以保存的常用的值的类型(这些类型在atomic头文件中都有自己的定义)如下表:
类型 | atomic内部定义 | 描述 |
bool | atomic_bool | |
char | atomic_char | atomics for fundamental integral types. These are either typedefs of the corresponding full specialization of the atomic class template or a base class of such specialization. |
signed char | atomic_schar | |
unsigned char | atomic_uchar | |
short | atomic_short | |
unsigned short | atomic_ushort | |
int | atomic_int | |
unsigned int | atomic_uint | |
long | atomic_long | |
unsigned long | atomic_ulong | |
long long | atomic_llong | |
unsigned long long | atomic_ullong | |
wchar_t | atomic_wchar_t | |
char16_t | atomic_char16_t | |
char32_t | atomic_char32_t | |
intmax_t | atomic_intmax_t | atomics for width-based integrals (those defined in ). Each of these is either an alias of one of the above atomics for fundamental integral types or of a full specialization of the atomic class template with an extended integral type. Where N is one in 8, 16, 32, 64, or any other type width supported by the library. |
uintmax_t | atomic_uintmax_t | |
int_leastN_t | atomic_int_leastN_t | |
uint_leastN_t | atomic_uint_leastN_t | |
int_fastN_t | atomic_int_fastN_t | |
uint_fastN_t | atomic_uint_fastN_t | |
intptr_t | atomic_intptr_t | |
uintptr_t | atomic_uintptr_t | |
size_t | atomic_size_t | |
ptrdiff_t | atomic_ptrdiff_t |
总的来说可以总结为,bool和int类(char也可以归为int)类型。
构造函数 | |
default (1) | atomic() noexcept = default; |
initialization (2) | constexpr atomic (T val) noexcept; |
copy [deleted] (3) | atomic (const atomic&) = delete; |
容易看出atomic对象是不可复制的。
=号操作符 | |
set value (1) | T operator= (T val) noexcept; |
T operator= (T val) volatile noexcept; | |
copy [deleted] (2) | atomic& operator= (const atomic&) = delete; |
atomic& operator= (const atomic&) volatile = delete; |
由上表得知,atomic对象可以用其内部存储类型赋值,但是atomic本身是不能进赋值的。
atomic经常用的函数有store和load,如下:
store函数 |
---|
void store (T val, memory_order sync = memory_order_seq_cst) volatile noexcept; |
void store (T val, memory_order sync = memory_order_seq_cst) noexcept; |
其实就是用val替换内部保存的值。内部替换的时候其实是加了线程同步的,所以不用担心多线程访问的问题。
load函数 |
---|
T load (memory_order sync = memory_order_seq_cst) const volatile noexcept; |
T load (memory_order sync = memory_order_seq_cst) const noexcept; |
就是返回内部保存的值,其实就是访问内部值,没什么要特别说明的。