C++ 多线程同步:原子操作(atomic)实战
原子操作的引入背景
在互斥锁章节中,我们学习了通过阻塞线程的方式实现临界区保护。但互斥锁存在上下文切换开销,在一些简单的同步场景中显得过于笨重。比如对单个变量的自增、自减、赋值等操作,我们需要一种更轻量级的同步方案——原子操作。
注意事项:原子操作仅适用于单个变量的简单同步,无法替代互斥锁实现复杂临界区的保护。
举个例子,使用互斥锁保护变量自增:
#include <iostream>
#include <thread>
#include <mutex>
using namespace std;
int count = 0;
mutex mtx;
void increment() {
for (int i = 0; i < 100000; ++i) {
lock_guard<mutex> lock(mtx);
count++;
}
}
int main() {
thread t1(increment);
thread t2(increment);
t1.join();
t2.join();
cout << "最终 count 值:" << count << endl;
return 0;
}


