最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
C++内存序六件套:从严格同步到自由放任
时间:2026-05-22 09:30:01 编辑:袖梨 来源:一聚教程网
C++内存序既是性能优化的利器,也是并发编程的暗礁。本文将深入解析六种内存序的使用场景,帮助开发者避开陷阱,充分发挥多线程潜力。

C++的这几种内存序用好了能提升性能,用错了可能导致难以调试的问题。
原子操作与内存序枚举
1. std::atomic 的常用操作
基础的加载与存储操作
std::atomic<int> flag{ 0 };
int a = flag.load(); // 读取操作
flag.store(1); // 写入操作
load方法用于原子地获取原子对象的值,store方法则原子地将值替换成非原子参数。默认情况下它们都使用memory_order_seq_cst内存序。
复合原子操作
- exchange():原子地替换值并返回旧值。
int main()
{
std::atomic<int> flag(0);
int old = flag.exchange(1); // 原子地设为1,返回旧值0
std::cout << "旧值: " << old << ", 新值: " << flag.load() << std::endl;
// 输出: 旧值: 0, 新值: 1
}
- compare_exchange_weak() / compare_exchange_strong():只有当当前值等于期望值时才替换成新值,否则将当前值写入期望值,返回值表示是否替换成功。
weak版本可能出现虚假失败,必须在循环中使用,但在某些平台上性能更好。strong版本保证只有值真正不同时才失败,更直观。
std::atomic<int> counter(0);void increment()
{
int expected = counter.load();
while (!counter.compare_exchange_weak(expected, expected + 1))
{
// 失败时 expected 已被更新为当前值,再次尝试
}
}int main()
{
std::vector threads;
for (int i = 0; i < 10; ++i)
threads.emplace_back(increment);
for (auto& t : threads)
t.join();
std::cout << "最终计数: " << counter << std::endl; // 10
}
- fetch_add() / fetch_sub():对整数或指针原子地执行加/减,返回旧值。
std::atomic<int> total(0);void add(int n)
{
for (int i = 0; i < 1000; ++i)
total.fetch_add(n);
}int main()
{
std::vector threads;
for (int i = 0; i < 4; ++i)
threads.emplace_back(add, 1
相关文章
-
ChatGPT之父为何被解雇?背后3个真相
05-22
-
ChatGPT读法怎么读才对?3种读音一次搞清
05-22
-
游戏里的数据玩家指的是什么?5个核心特征让你快速识别
05-22
-
HTML组件化:基础标签到高级应用视图的演进之路
05-22
-
OpenProcessToken在系统安全漏洞中的角色分析
05-22
-
Debian系统维护中CPUInfo工具的使用方法与技巧
05-22