atomic笔记

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 都是自减后的新值
相关推荐
hanlin036 小时前
刷题笔记:力扣第32题-最长有效括号
笔记·算法·leetcode
All for pursuit.6 小时前
【动态规划-21】312.戳气球
数据结构·c++·算法·leetcode·动态规划
xian_wwq7 小时前
【学习笔记】Milvus 如何完成一次向量相似度检索,Milvus 索引到底应该怎么选?-15
笔记·学习·milvus
碧海银沙音频科技研究院9 小时前
基于炬芯ATS3089X自研AEC声学回声消除算法
算法
通问AI9 小时前
在两台 Mac Studio 上跑 800B 模型:MLX + RDMA over Thunderbolt 实测与四道门选型法
算法
ZywOo6239 小时前
《算法竞赛进阶指南》0x03 前缀和与差分
算法
Scintilla_y9 小时前
DAY2 滑动窗口
算法·leetcode·散列表
lvwangshu9 小时前
笛卡尔树
算法·图论
026d239 小时前
状态信号只知“其然”不知“其所以然”:变工况机械故障诊断的物理盲区
算法
姜鱼问生10 小时前
备份和服务器在同一台机器上,等于没备份
算法·架构