std::atomic<int> counter{0};
void worker() {
for (int i = 0; i < 100000; i++) {
counter.fetch_add(1); // 原子自增
}
}
std::mutex mtx;
std::map<int, std::string> cache;
void update(int k, std::string v) {
std::lock_guard<std::mutex> lock(mtx);
cache[k] = v; // 保护复杂操作
}
| 场景 | 推荐 | 原因 |
|---|---|---|
| 单个计数器/标志位 | atomic | 开销极小 |
| 简单数值更新 | atomic | 无锁,不阻塞 |
| 保护复杂容器/多步骤操作 | mutex | 原子只适用单变量 |
| 需要条件等待 | mutex+condvar | atomic 无法等待 |
atomic 默认用最保守的 memory_order_seq_cst。高并发性能场景可用更弱的内存序:
// 发布-订阅模式
flag.store(true, std::memory_order_release);
if (flag.load(std::memory_order_acquire)) { ... }
建议:先保证正确性用默认内存序,profile 确认是瓶颈后再优化内存序。不要一开始就追求无锁。