
在C++多线程编程中,当多个线程需要访问共享资源时,如果读操作远多于写操作,使用普通的互斥锁(std::mutex)会降低并发性能。因为互斥锁无论读写都独占资源,而实际上多个读操作可以同时进行。这时候就需要用到 std::shared_mutex —— 它支持共享所有权,实现读写锁机制:允许多个线程同时读(共享模式),但写操作必须独占(独占模式)。
std::shared_mutex 是 C++17 引入的标准库组件,定义在头文件 <shared_mutex> 中。它支持两种加锁方式:
lock_shared() 或 try_lock_shared() 获取,用于读操作,可被多个线程同时持有。lock() 或 try_lock() 获取,用于写操作,只能由一个线程持有,且不能与共享锁共存。对应的,我们通常使用 std::shared_lock 来管理共享锁,用 std::unique_lock 管理独占锁。
下面是一个典型示例:多个线程对一个共享的整数容器进行读写操作,使用 std::shared_mutex 保证线程安全。
立即学习“C++免费学习笔记(深入)”;
#include <iostream>
#include <vector>
#include <thread>
#include <shared_mutex>
#include <chrono>
#include <numeric>
<p>std::vector<int> data = {1, 2, 3, 4, 5};
std::shared_mutex smtx; // 共享互斥量</p><p>// 读操作:计算总和
void reader(int id) {
std::shared_lock<std::shared_mutex> lock(smtx); // 获取共享锁
std::this_thread::sleep_for(std::chrono::milliseconds(100)); // 模拟处理时间
int sum = std::accumulate(data.begin(), data.end(), 0);
std::cout << "Reader " << id << " sees sum: " << sum << "\n";
}</p><p>// 写操作:向容器添加一个元素
void writer(int id) {
std::unique_lock<std::shared_mutex> lock(smtx); // 获取独占锁
std::this_thread::sleep_for(std::chrono::milliseconds(200));
int new_val = id * 10;
data.push_back(new_val);
std::cout << "Writer " << id << " added: " << new_val << "\n";
}</p><p>int main() {
std::vector<std::thread> threads;</p><pre class='brush:php;toolbar:false;'>// 启动3个写线程和5个读线程
for (int i = 0; i < 3; ++i) {
threads.emplace_back(writer, i + 1);
}
for (int i = 0; i < 5; ++i) {
threads.emplace_back(reader, i + 1);
}
// 等待所有线程完成
for (auto& t : threads) {
t.join();
}
return 0;}
输出可能类似:
Reader 1 sees sum: 15 Writer 1 added: 10 Reader 2 sees sum: 25 Reader 3 sees sum: 25 Writer 2 added: 20 Reader 4 sees sum: 35 Reader 5 sees sum: 35 Writer 3 added: 30
可以看到:
使用 std::shared_mutex 时注意以下几点:
基本上就这些。std::shared_mutex 在读多写少的场景下能显著提升并发效率,是多线程编程中非常实用的同步工具。合理使用 shared_lock 和 unique_lock 配合 shared_mutex,可以让代码更清晰、安全。
以上就是c++++中std::shared_mutex(读写锁)的使用_c++多线程读写锁同步实例的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号