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_);