当前位置: 代码迷 >> 综合 >> C++并发编程之读写锁(C++17)
  详细解决方案

C++并发编程之读写锁(C++17)

热度:89   发布时间:2024-01-20 02:04:21.0

STL 和 Boost 都提供了 shared_mutex 来解决「读者-写者」问题(必须使用C++17或者后续版本)。shared_mutex 这个名字并不十分贴切,不如 pthread 直呼「读写锁」。

所谓「读写锁」,就是同时可以被多个读者拥有,但是只能被一个写者拥有的锁。而所谓「多个读者、单个写者」,并非指程序中只有一个写者(线程),而是说不能有多个写者同时去写。

下面看一个计数器的例子。

class Counter {
public:Counter() : value_(0) {}// Multiple threads/readers can read the counter's value at the same time.std::size_t Get() const {std::shared_lock<std::shared_mutex> lock(mutex_);return value_;}// Only one thread/writer can increment/write the counter's value.void Increase() {// You can also use lock_guard here.std::unique_lock<std::shared_mutex> lock(mutex_);value_++;}// Only one thread/writer can reset/write the counter's value.void Reset() {std::unique_lock<std::shared_mutex> lock(mutex_);
  相关解决方案