答案:C++中读写锁允许多个读线程共享访问、写线程独占访问,C++14起推荐使用std::shared_mutex实现,支持lock_shared()和lock()操作,读写互斥且写时禁止读;示例代码展示了5个读线程和2个写线程对共享数据的并发访问控制。

在C++中实现读写锁(Read-Write Lock),核心目标是允许多个读线程同时访问共享资源,但写线程独占访问。也就是说:读共享、写独占、写时禁止读。
使用实现读写锁(C++14及以上)
C++14起,std::sha_mutex 提供了对读写锁的原生支持,是最推荐的方式。
示例代码:
#include <iostream><br>#include <thread><br>#include <vector><br>#include <shared_mutex><br>#include <chrono> <p>std::shared_mutex rw_mutex; int shared_data = 0;</p><p>void reader(int id) { rw_mutex.lock_shared(); // 获取读锁 std::cout << "Reader " << id << " reads data: " << shared_data << "n"; std::this_thread::sleep_for(std::chrono::milliseconds(100)); // 模拟读操作 rw_mutex.unlock_shared(); // 释放读锁 }</p><p>void writer(int id) { rw_mutex.lock(); // 获取写锁(独占) std::cout << "Writer " << id << " writes data.n"; shared_data++; std::this_thread::sleep_for(std::chrono::milliseconds(200)); rw_mutex.unlock(); // 释放写锁 }</p><p>int main() { std::vector<std::thread> threads; for (int i = 0; i < 5; ++i) { threads.emplace_back(reader, i); } for (int i = 0; i < 2; ++i) { threads.emplace_back(writer, i); } for (auto& t : threads) { t.join(); } return 0; }
说明:
– lock_shared():多个线程可同时获取读锁。
– lock():写锁是独占的,任一时刻只能一个线程持有。
– C++17还提供 std::shared_timed_mutex,支持带超时的锁操作。
手动实现简易读写锁(基于互斥量)
若环境不支持 std::shared_mutex,可以用 std::mutex 和条件变量模拟。
基本思路:
- 用一个互斥量保护读写状态
- 维护当前活跃读线程数
- 写线程需等待所有读线程退出后才能进入
代码实现:
立即学习“”;
#include <mutex><br>#include <condition_variable> <p>class ReadWriteLock { private: std::mutex mtx; std::condition_variable cv; int read_count = 0; bool writing = false;</p><p>public: void lock_read() { std::unique_lock<std::mutex> lock(mtx); cv.wait(lock, [this] { return !writing; }); ++read_count; lock.unlock(); }</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">void unlock_read() { std::lock_guard<std::mutex> lock(mtx); --read_count; if (read_count == 0) { cv.notify_all(); } } void lock_write() { std::unique_lock<std::mutex> lock(mtx); cv.wait(lock, [this] { return !writing && read_count == 0; }); writing = true; } void unlock_write() { std::lock_guard<std::mutex> lock(mtx); writing = false; cv.notify_all(); }
};
用火龙果,轻松写作,通过校对、改写、扩展等功能实现高质量内容生产。
106 使用方式与标准库类似,但注意这种实现可能有性能开销和公平性问题(比如写线程可能饿死)。
使用场景与注意事项
读写锁适合读多写少的场景,如缓存、配置管理等。
- 避免在持有读锁时尝试获取写锁,容易死锁
- 频繁写入时,读写锁可能不如普通互斥锁高效
- 某些系统提供 pthread_rwlock_t(POSIX),也可封装使用
基本上就这些。优先使用 std::shared_mutex,简洁安全。需要兼容旧标准时再考虑手动实现。
以上就是++怎么实现一个读写锁_c++读写锁read-write lock实现方法的详细内容,更多请关注php中文网其它相关文章!
微信扫一扫打赏
支付宝扫一扫打赏
