互斥与同步
当多个线程同时访问共享数据时,如果没有正确的同步机制,程序就会产生数据竞争(data race),导致未定义行为。本节系统讲解 C++ 标准库提供的互斥量(mutex)和同步原语,帮助你安全地协调线程间的数据访问与通信。
数据竞争
当两个或更多线程并发访问同一内存位置,且其中至少一个是写操作,同时没有同步机制保护时,就构成了数据竞争。C++ 标准明确规定:数据竞争是未定义行为(Undefined Behavior),编译器和硬件不保证任何结果。
下面是一个经典的"坏"示例 — 多线程无保护地递增计数器:
#include <iostream>
#include <thread>
#include <vector>
int counter = 0; // 共享数据,无保护
void increment(int n) {
for (int i = 0; i < n; ++i) {
++counter; // 数据竞争!读-改-写并非原子操作
}
}
int main() {
constexpr int num_threads = 10;
constexpr int per_thread = 100'000;
std::vector<std::jthread> threads;
for (int i = 0; i < num_threads; ++i) {
threads.emplace_back(increment, per_thread);
}
threads.clear(); // 等待所有线程结束
// 期望输出 1000000,实际结果几乎总是小于该值
std::cout << "counter = " << counter << "\n";
}
++counter 看似一条语句,实际上包含三步:读取当前值、加一、写回。多线程同时执行这三步时,某些增量会"丢失"。
std::mutex
std::mutex 是最基本的互斥量,提供排他性所有权。同一时刻只有一个线程可以持有锁。
#include <mutex>
std::mutex mtx;
int counter = 0;
void increment(int n) {
for (int i = 0; i < n; ++i) {
mtx.lock();
++counter;
mtx.unlock();
}
}
这段代码正确保护了 counter,但手动调用 lock()/unlock() 非常危险:
void dangerous_function() {
mtx.lock();
// 如果这里抛出异常,unlock() 永远不会执行 → 死锁!
do_something_that_might_throw();
if (some_condition) {
return; // 忘记 unlock → 死锁!
}
mtx.unlock();
}
std::scoped_lock (C++17)
std::scoped_lock 是 C++17 引入的 RAII 锁管理器,构造时加锁,析构时自动解锁。它是 std::lock_guard 的增强版,支持同时锁定多个互斥量且保证无死锁。
#include <mutex>
#include <thread>
#include <vector>
#include <iostream>
std::mutex mtx;
int counter = 0;
void increment(int n) {
for (int i = 0; i < n; ++i) {
std::scoped_lock lk(mtx); // 构造加锁,离开作用域自动解锁
++counter;
}
}
int main() {
std::vector<std::jthread> threads;
for (int i = 0; i < 10; ++i) {
threads.emplace_back(increment, 100'000);
}
threads.clear();
std::cout << "counter = " << counter << "\n"; // 输出 1000000
}
锁定多个互斥量时,std::scoped_lock 使用内部死锁避免算法(等价于 std::lock):
std::mutex m1, m2;
void transfer(Account& from, Account& to, int amount) {
// 无论 from/to 的顺序如何,都不会死锁
std::scoped_lock lk(m1, m2);
from.balance -= amount;
to.balance += amount;
}
std::lock_guard。对单个 mutex,两者行为一致;对多个 mutex,scoped_lock 自动避免死锁。
std::unique_lock
std::unique_lock 比 scoped_lock 更灵活,支持:延迟加锁、尝试加锁、超时加锁、手动解锁/重新加锁,以及与条件变量配合使用。
#include <mutex>
#include <chrono>
std::mutex mtx;
void deferred_locking() {
// 构造时不加锁
std::unique_lock lk(mtx, std::defer_lock);
// ... 做一些不需要锁的准备工作 ...
lk.lock(); // 显式加锁
// 临界区
} // 析构自动解锁
void try_locking() {
std::unique_lock lk(mtx, std::try_to_lock);
if (lk.owns_lock()) {
// 成功获取锁,执行临界区
} else {
// 获取失败,做其他事情
}
}
void timed_locking() {
std::timed_mutex tmtx;
std::unique_lock lk(tmtx, std::chrono::milliseconds(100));
if (lk.owns_lock()) {
// 在 100ms 内成功获取锁
}
}
unique_lock 是使用 std::condition_variable 的必要搭配(scoped_lock 不支持 condition_variable):
std::mutex mtx;
std::condition_variable cv;
bool ready = false;
void wait_for_signal() {
std::unique_lock lk(mtx); // condition_variable 要求 unique_lock
cv.wait(lk, [] { return ready; });
// 被唤醒且 ready == true
}
std::condition_variable
条件变量用于线程间的事件通知:一个线程等待某个条件成立,另一个线程在条件成立时发出通知。
wait / notify 模式
#include <condition_variable>
#include <mutex>
#include <iostream>
#include <thread>
std::mutex mtx;
std::condition_variable cv;
bool data_ready = false;
void producer() {
{
std::scoped_lock lk(mtx);
// 准备数据 ...
data_ready = true;
} // 释放锁后再通知,避免被唤醒的线程立即阻塞在锁上
cv.notify_one();
}
void consumer() {
std::unique_lock lk(mtx);
// wait(lock, predicate):等待直到 predicate 返回 true
cv.wait(lk, [] { return data_ready; });
// 此处 lk 仍然持有锁,data_ready == true
std::cout << "数据已就绪,开始处理\n";
}
wait() 必须搭配谓词(predicate)使用,或者在循环中检查条件:
// 方式一:谓词重载(推荐)
cv.wait(lk, [] { return data_ready; });
// 方式二:等价的循环写法
while (!data_ready) {
cv.wait(lk);
}
生产者-消费者队列
这是条件变量最经典的应用场景:
#include <condition_variable>
#include <mutex>
#include <queue>
#include <thread>
#include <iostream>
template <typename T>
class ThreadSafeQueue {
std::queue<T> queue_;
mutable std::mutex mtx_;
std::condition_variable cv_;
public:
void push(T value) {
{
std::scoped_lock lk(mtx_);
queue_.push(std::move(value));
}
cv_.notify_one(); // 通知一个等待的消费者
}
T pop() {
std::unique_lock lk(mtx_);
cv_.wait(lk, [this] { return !queue_.empty(); });
T value = std::move(queue_.front());
queue_.pop();
return value;
}
bool try_pop(T& value) {
std::scoped_lock lk(mtx_);
if (queue_.empty()) return false;
value = std::move(queue_.front());
queue_.pop();
return true;
}
};
int main() {
ThreadSafeQueue<int> q;
// 生产者线程
std::jthread producer([&q](std::stop_token st) {
for (int i = 0; i < 20 && !st.stop_requested(); ++i) {
q.push(i);
std::cout << "生产: " << i << "\n";
}
q.push(-1); // 哨兵值,通知消费者结束
});
// 消费者线程
std::jthread consumer([&q] {
while (true) {
int val = q.pop();
if (val == -1) break;
std::cout << "消费: " << val << "\n";
}
});
}
notify_one() 唤醒一个等待线程,适合单消费者或任务分发场景。notify_all() 唤醒所有等待线程,适合广播式通知(如"数据已准备好,所有消费者都可以开始")。
死锁避免
死锁发生的四个必要条件:互斥、占有并等待、不可抢占、循环等待。只要破坏其中任何一个,就可以避免死锁。
策略一:固定锁顺序
// 如果必须同时持有多个锁,所有线程按相同顺序加锁
// 例如:总是先锁 ID 较小的对象
void transfer(Account& a, Account& b, int amount) {
Account& first = (a.id < b.id) ? a : b;
Account& second = (a.id < b.id) ? b : a;
std::scoped_lock lk(first.mtx, second.mtx);
// ...
}
策略二:使用 std::scoped_lock
// scoped_lock 内部使用死锁避免算法,无需手动排序
void transfer(Account& a, Account& b, int amount) {
std::scoped_lock lk(a.mtx, b.mtx); // 自动避免死锁
a.balance -= amount;
b.balance += amount;
}
策略三:缩小锁的范围
// 避免在持有锁时调用未知代码(回调、虚函数)
void bad_design() {
std::scoped_lock lk(mtx);
callback(); // 危险!callback 内部可能尝试获取另一个锁
}
void good_design() {
Data local_copy;
{
std::scoped_lock lk(mtx);
local_copy = shared_data; // 在锁内拷贝
}
callback(local_copy); // 在锁外调用回调
}
std::shared_mutex(读写锁)
很多场景下读操作远多于写操作(如配置查询、缓存读取)。std::shared_mutex(C++17)允许多个线程同时读,但写时独占。
#include <shared_mutex>
#include <unordered_map>
#include <string>
class ThreadSafeCache {
mutable std::shared_mutex mtx_;
std::unordered_map<std::string, int> cache_;
public:
// 读操作:使用 shared_lock,允许多线程并发读
std::optional<int> get(const std::string& key) const {
std::shared_lock lk(mtx_); // 共享锁(读锁)
auto it = cache_.find(key);
if (it != cache_.end()) return it->second;
return std::nullopt;
}
// 写操作:使用 unique_lock,独占访问
void set(const std::string& key, int value) {
std::unique_lock lk(mtx_); // 独占锁(写锁)
cache_[key] = value;
}
// 删除操作:也需要独占锁
void erase(const std::string& key) {
std::unique_lock lk(mtx_);
cache_.erase(key);
}
};
shared_mutex 的额外开销可能抵消并发收益,此时普通 std::mutex 反而更快。
锁类型与互斥量的搭配关系:
| 锁类型 | 搭配的互斥量 | 语义 |
|---|---|---|
std::scoped_lock | 任意 Lockable | RAII 独占锁,支持多个 mutex |
std::unique_lock | 任意 Lockable | 灵活独占锁,支持条件变量 |
std::shared_lock | shared_mutex | 共享锁(读锁) |
本节小结
- 数据竞争是未定义行为,对共享可变数据的并发访问必须同步
- 永远使用 RAII 锁(
scoped_lock、unique_lock),不要手动 lock/unlock - std::scoped_lock 是默认首选,支持多 mutex 无死锁加锁
- std::unique_lock 用于需要延迟加锁、超时或配合条件变量的场景
- 条件变量实现等待-通知模式,必须搭配谓词防止虚假唤醒
- 避免死锁:固定锁顺序、使用 scoped_lock 多锁版本、缩小临界区
- shared_mutex 适合读多写少场景,用 shared_lock 读、unique_lock 写