atomic笔记
C++ 中实现原子操作、解决多线程数据竞争的核心工具
初始化
cpp
// 直接初始化(推荐)
std::atomic<int> a2(10);
// 赋值初始化(C++17 后支持)
std::atomic<int> a3 = 20;
读 store
cpp
// 写操作:两种方式等价
num.store(10); // 显式写(推荐,可指定内存序,后面讲)
num = 20; // 隐式写(等价于 num.store(20))
写 load
cpp
// 读操作:两种方式等价
int val1 = num.load(); // 显式读
int val2 = num; // 隐式读
改 exchange
cpp
std::atomic<int> num(10);
// 准备要替换的新值
int new_val = 20;
// 执行原子交换:返回旧值,同时将num设为新值
int old_val = num.exchange(new_val);
判断是否改变
cpp
std::atomic<int> value(true); // 等价于 value = 1
int new_val = false; // 等价于 new_val = 0
if (value.exchange(new_val) != new_val) {
std::cout << "变量已改变" << std::endl; // 会执行这行
} else {
std::cout << "变量未改变" << std::endl;
}
自增 fetch_add ++ 与 自减 fetch_sub --
| 原子操作 | 等价写法 | 核心一致点 |
|---|---|---|
| auto temp = num++; | auto temp = num.fetch_add(1); | temp 都是自增前的旧值 |
| auto temp = ++num; | auto temp = num.fetch_add(1) + 1; | temp 都是自增后的新值 |
| auto temp = num--; | auto temp = num.fetch_sub(1); | temp 都是自减前的旧值 |
| auto temp = --num; | auto temp = num.fetch_sub(1) - 1; | temp 都是自减后的新值 |