1. 为什么我们需要原子操作
十年前我第一次接触多线程编程时,遇到过一个诡异的bug:一个简单的计数器在20个线程同时操作时,结果总是不正确。当时花了三天时间才明白,这是因为普通的变量操作在多线程环境下不是原子性的。这个经历让我深刻理解了原子操作的重要性。
原子操作(atomic operation)指的是不可被中断的一个或一系列操作。就像它的名字"原子"所暗示的,这些操作是最小的、不可分割的执行单元。在多线程环境中,当多个线程同时访问和修改同一个共享变量时,如果没有适当的同步机制,就会导致数据竞争(data race)和不确定的行为。
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. 原子操作与互斥锁的对比
2.1 性能差异实测
让我们通过一个实际的例子来比较互斥锁和原子操作的性能差异。我们创建一个简单的计数器,让20个线程各自进行10万次加1和减1操作:
cpp复制#include <iostream>
#include <thread>
#include <atomic>
#include <mutex>
#include <chrono>
constexpr int MAX = 100000;
constexpr int THREAD_COUNT = 20;
// 普通变量
int normal_total = 0;
// 原子变量
std::atomic<int> atomic_total(0);
// 互斥锁保护的变量
int mutex_total = 0;
std::mutex mtx;
void normal_thread() {
for (int i = 0; i < MAX; ++i) {
normal_total += 1;
normal_total -= 1;
}
}
void atomic_thread() {
for (int i = 0; i < MAX; ++i) {
atomic_total += 1;
atomic_total -= 1;
}
}
void mutex_thread() {
for (int i = 0; i < MAX; ++i) {
mtx.lock();
mutex_total += 1;
mutex_total -= 1;
mtx.unlock();
}
}
int main() {
auto start = std::chrono::high_resolution_clock::now();
std::thread t1[THREAD_COUNT];
for (int i = 0; i < THREAD_COUNT; ++i) {
t1[i] = std::thread(normal_thread);
}
for (int i = 0; i < THREAD_COUNT; ++i) {
t1[i].join();
}
auto end = std::chrono::high_resolution_clock::now();
std::cout << "Normal result: " << normal_total
<< ", time: " << std::chrono::duration_cast<std::chrono::milliseconds>(end-start).count() << "ms\n";
start = std::chrono::high_resolution_clock::now();
std::thread t2[THREAD_COUNT];
for (int i = 0; i < THREAD_COUNT; ++i) {
t2[i] = std::thread(atomic_thread);
}
for (int i = 0; i < THREAD_COUNT; ++i) {
t2[i].join();
}
end = std::chrono::high_resolution_clock::now();
std::cout << "Atomic result: " << atomic_total
<< ", time: " << std::chrono::duration_cast<std::chrono::milliseconds>(end-start).count() << "ms\n";
start = std::chrono::high_resolution_clock::now();
std::thread t3[THREAD_COUNT];
for (int i = 0; i < THREAD_COUNT; ++i) {
t3[i] = std::thread(mutex_thread);
}
for (int i = 0; i < THREAD_COUNT; ++i) {
t3[i].join();
}
end = std::chrono::high_resolution_clock::now();
std::cout << "Mutex result: " << mutex_total
<< ", time: " << std::chrono::duration_cast<std::chrono::milliseconds>(end-start).count() << "ms\n";
return 0;
}
在我的机器上(i7-10700K,Windows 10,VS2022),运行结果如下:
code复制Normal result: 124, time: 15ms
Atomic result: 0, time: 187ms
Mutex result: 0, time: 423ms
可以看到:
- 普通变量操作最快但结果错误
- 原子操作比互斥锁快约2.3倍
- 互斥锁最慢但结果正确
2.2 底层实现原理
原子操作的性能优势来自于它的底层实现方式。互斥锁是通过操作系统提供的同步原语实现的,每次加锁和解锁都需要从用户态切换到内核态,这种上下文切换开销很大。
而原子操作通常是通过CPU提供的特殊指令实现的,比如x86架构上的LOCK前缀指令。这些指令直接在硬件层面保证了操作的原子性,不需要操作系统的介入。现代CPU通常会在指令流水线中专门优化这些原子指令的执行。
3. C++中的原子类型
3.1 标准原子类型
C++11在<atomic>头文件中提供了一系列原子类型:
| 原子类型 | 对应普通类型 | 说明 |
|---|---|---|
| atomic_bool | bool | 布尔型 |
| atomic_char | char | 字符型 |
| atomic_int | int | 整型 |
| atomic_long | long | 长整型 |
| atomic_llong | long long | 长长整型 |
| atomic_uchar | unsigned char | 无符号字符 |
