std::shared_mutex
什么是 std::shared_mutex
std::shared_mutex 是 C++17 在 <shared_mutex> 头文件中引入的一种读写互斥锁(readers-writer mutex)。它支持两种锁定模式:
- 独占锁定(exclusive):只有一个线程能持有,其他线程既不能读也不能写——用于写操作
- 共享锁定(shared):多个线程可以同时持有,但不能和独占锁定共存——用于读操作
这种设计特别适合"读多写少"的场景:多个读线程可以并发地读取共享数据(因为读操作不修改数据,不会互相冲突),只有写操作才需要独占访问。
C++14 已经有了 std::shared_timed_mutex(支持超时锁定),C++17 的 std::shared_mutex 去掉了超时功能,更轻量。如果不需要超时锁定,优先用 std::shared_mutex。
头文件
#include <shared_mutex> // std::shared_mutex, std::shared_lock
#include <mutex> // std::unique_lock, std::lock_guard核心接口
| 操作 | 方法 | 说明 |
|---|---|---|
| 独占锁定 | lock() | 获取独占锁(写锁),阻塞直到成功 |
| 独占尝试锁定 | try_lock() | 尝试获取独占锁,立即返回 |
| 独占解锁 | unlock() | 释放独占锁 |
| 共享锁定 | lock_shared() | 获取共享锁(读锁),阻塞直到成功 |
| 共享尝试锁定 | try_lock_shared() | 尝试获取共享锁,立即返回 |
| 共享解锁 | unlock_shared() | 释放共享锁 |
推荐使用 RAII 锁管理器而不是直接调用 lock/unlock:
- 写操作:
std::unique_lock<std::shared_mutex>或std::lock_guard<std::shared_mutex> - 读操作:
std::shared_lock<std::shared_mutex>
基本示例
#include <iostream>
#include <shared_mutex>
#include <mutex>
#include <thread>
#include <vector>
#include <string>
#include <chrono>
#include <map>
// ============================
// 示例1:线程安全的计数器
// ============================
class ThreadSafeCounter {
mutable std::shared_mutex mutex_; // mutable 因为 const 方法也需要加锁
int value_ = 0;
public:
// 读操作:共享锁,多个线程可以同时读
int get() const {
std::shared_lock lock(mutex_); // CTAD 自动推导类型
return value_;
}
// 写操作:独占锁,只有一个线程能写
void increment() {
std::unique_lock lock(mutex_);
++value_;
}
void reset() {
std::unique_lock lock(mutex_);
value_ = 0;
}
};
void counter_demo() {
ThreadSafeCounter counter;
// 多个读线程 + 一个写线程
auto writer = std::thread([&counter]() {
for (int i = 0; i < 100; ++i) {
counter.increment();
std::this_thread::sleep_for(std::chrono::microseconds(10));
}
});
std::vector<std::thread> readers;
for (int i = 0; i < 4; ++i) {
readers.emplace_back([&counter, i]() {
for (int j = 0; j < 50; ++j) {
int val = counter.get(); // 多个读线程同时读取不会阻塞
if (j == 49) {
std::cout << "读线程" << i << " 最后读到: " << val << std::endl;
}
std::this_thread::sleep_for(std::chrono::microseconds(5));
}
});
}
writer.join();
for (auto& t : readers) t.join();
std::cout << "最终值: " << counter.get() << std::endl;
}
// ============================
// 示例2:线程安全的缓存(读多写少的典型场景)
// ============================
class ThreadSafeCache {
mutable std::shared_mutex mutex_;
std::map<std::string, std::string> data_;
public:
// 读取缓存(高频操作)——共享锁
std::string get(const std::string& key) const {
std::shared_lock lock(mutex_);
auto it = data_.find(key);
if (it != data_.end()) {
return it->second;
}
return ""; // 未找到
}
// 检查是否存在——共享锁
bool contains(const std::string& key) const {
std::shared_lock lock(mutex_);
return data_.count(key) > 0;
}
// 写入缓存(低频操作)——独占锁
void put(const std::string& key, const std::string& value) {
std::unique_lock lock(mutex_);
data_[key] = value;
}
// 删除缓存项——独占锁
void erase(const std::string& key) {
std::unique_lock lock(mutex_);
data_.erase(key);
}
// 获取缓存大小——共享锁
std::size_t size() const {
std::shared_lock lock(mutex_);
return data_.size();
}
};
void cache_demo() {
ThreadSafeCache cache;
// 写线程:填充缓存
auto writer = std::thread([&cache]() {
for (int i = 0; i < 20; ++i) {
cache.put("key" + std::to_string(i), "value" + std::to_string(i));
std::this_thread::sleep_for(std::chrono::milliseconds(5));
}
});
// 多个读线程:并发读取
std::vector<std::thread> readers;
for (int r = 0; r < 4; ++r) {
readers.emplace_back([&cache, r]() {
int found = 0;
for (int i = 0; i < 100; ++i) {
auto val = cache.get("key" + std::to_string(i % 20));
if (!val.empty()) ++found;
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
std::cout << "读线程" << r << " 命中: " << found << "/100" << std::endl;
});
}
writer.join();
for (auto& t : readers) t.join();
std::cout << "缓存大小: " << cache.size() << std::endl;
}
// ============================
// 示例3:配置热更新
// ============================
class Config {
mutable std::shared_mutex mutex_;
std::map<std::string, std::string> settings_;
public:
// 读取配置(频繁调用)
std::string get_setting(const std::string& key) const {
std::shared_lock lock(mutex_);
auto it = settings_.find(key);
return (it != settings_.end()) ? it->second : "";
}
// 批量更新配置(偶尔调用)
void update_settings(const std::map<std::string, std::string>& new_settings) {
std::unique_lock lock(mutex_); // 独占锁,阻塞所有读线程
for (const auto& [key, value] : new_settings) {
settings_[key] = value;
}
}
};
int main() {
std::cout << "=== 计数器 ===" << std::endl;
counter_demo();
std::cout << "\n=== 缓存 ===" << std::endl;
cache_demo();
return 0;
}shared_mutex vs mutex 的对比
| 特性 | std::mutex | std::shared_mutex |
|---|---|---|
| 锁模式 | 只有独占 | 独占 + 共享 |
| 多个读线程 | 互斥(串行) | 可并发 |
| 写线程 | 独占 | 独占 |
| 开销 | 较小 | 较大(维护读者计数) |
| 读多写少场景 | 性能差 | 性能好 |
| 写多读少场景 | 差异不大 | 可能更差(锁开销更大) |
| 头文件 | <mutex> | <shared_mutex> |
RAII 锁管理器对照
| 锁管理器 | 关联的锁模式 | 用途 |
|---|---|---|
std::lock_guard<std::shared_mutex> | 独占 | 最简单的写锁(无法手动解锁) |
std::unique_lock<std::shared_mutex> | 独占 | 灵活的写锁(可延迟、可手动解锁) |
std::shared_lock<std::shared_mutex> | 共享 | 读锁 |
适用场景
- 读多写少的共享数据结构:缓存、配置表、路由表
- DNS 缓存、用户会话存储等读取频率远高于更新频率的系统
- 数据库连接池的状态查询
- 日志级别等运行时可热更新的配置
常见问题
shared_mutex 一定比 mutex 快吗?
不一定。shared_mutex 内部需要维护共享锁的计数和状态,比 mutex 重。如果读写比例接近 1:1,或者临界区非常短(几条指令),mutex 可能反而更快。只有当读操作远多于写操作(比如 10:1 以上),且临界区有一定长度时,shared_mutex 才有明显优势。
写线程会不会被读线程饿死?
标准没有规定 shared_mutex 的调度策略。大多数实现会让等待中的写线程优先于新的读线程(写优先策略),避免写线程饿死。但具体行为取决于实现。
shared_lock 和 unique_lock 能在同一个 shared_mutex 上同时使用吗?
可以,但不能同时持有。shared_lock(共享锁)允许多个读线程同时持有;当某个线程用 unique_lock 获取独占锁时,所有 shared_lock 必须先释放。这就是读写锁的核心语义。
mutex_ 为什么要声明为 mutable?
因为读操作通常是 const 成员函数,但加锁/解锁需要修改 mutex 的内部状态。mutable 允许 const 方法修改 mutex 成员。
注意事项
shared_mutex不可拷贝、不可移动- 不要在持有共享锁的情况下尝试获取独占锁(会死锁)
- 不要在持有独占锁的情况下再次获取独占锁(
shared_mutex不是递归的) - 始终使用 RAII 锁管理器(
shared_lock、unique_lock),不要手动 lock/unlock - 如果临界区非常短,考虑用
std::mutex而不是shared_mutex——简单且开销更低 - 如果需要超时锁定功能,使用
std::shared_timed_mutex(C++14) - 读操作中不要意外修改共享数据(这会导致数据竞争,即使持有了共享锁)
编译器支持情况
| 编译器 | 最低支持版本 |
|---|---|
| GCC | 7.0 |
| Clang | 3.9 |
| MSVC | 19.10 (VS 2017) |
总结
std::shared_mutex 是 C++17 提供的读写互斥锁,专为"读多写少"的并发场景设计。它允许多个读线程同时访问共享数据(共享锁模式),同时保证写操作的独占性(独占锁模式)。配合 std::shared_lock(读锁)和 std::unique_lock(写锁)使用,代码简洁且异常安全。相比 std::mutex 的纯独占模式,shared_mutex 在读操作占主导的场景下能显著减少锁竞争、提高并发吞吐量。但它不是万能的——如果读写比例接近或临界区极短,普通 mutex 可能更合适。选择时需要根据实际的读写比例和临界区长度来评估。