How Does C++ Read-Write Lock (shared_mutex) Work?

Sometimes, we encounter a situation where: “many reads, very few writes.”

For example, configuration, status information, coordinate parameters, etc.

If all threads use <span>std::mutex</span>, then read operations will queue up, wasting performance, which is unfortunate 😅

To solve this problem, C++17 introduced a smarter lock 🔒: “std::shared_mutex”.

Why is it called a Read-Write Lock?

You might be confused by the name read-write lock 🤔:

How does shared_mutex become a “read-write lock”? How does it know whether I am reading or writing?

In fact, <span>std::mutex</span> itself does not know what you are doing; it simply provides two types of locking mechanisms:

  • “Shared Lock”: Allows multiple threads to hold it simultaneously
  • “Exclusive Lock”: Only one thread can hold it, blocking all read threads

“Therefore: shared_mutex is a capability provider. It does not automatically determine whether you are reading or writing; it depends on the type of lock you choose.”

  • <span>std::shared_lock<std::shared_mutex></span> → Acquires a “shared lock”, used for read operations, multiple threads can hold it simultaneously
  • <span>std::unique_lock<std::shared_mutex></span> → Acquires an “exclusive lock”, used for write operations, only one thread can hold it

Example Code

Let’s assume a typical “many reads, few writes” scenario:

  • Write thread: occasionally updates the status
  • Read thread: frequently reads the status
#include <shared_mutex>
#include <string>

class Config {
 public:
    void UpdateValue(const std::string& v) {
        std::unique_lock<std::shared_mutex> lock(mutex_);
        value_ = v; // Write operation
    }

    std::string GetValue() const {
        std::shared_lock<std::shared_mutex> lock(mutex_);
        return value_; // Read operation
    }

 private:
    mutable std::shared_mutex mutex_;
    std::string value_;
};

Overview of Read-Write Lock Concurrency Behavior

  1. Shared Read
  • Current lock type held: “Read Lock (shared_lock)”
  • Can other threads acquire a “Read” lock: “Allowed”
  • Can other threads acquire a “Write” lock: “Denied”
  • Explanation: “Read-Read” does not conflict, “Read-Write” conflicts
How Does C++ Read-Write Lock (shared_mutex) Work?
  1. Exclusive Write
  • Current lock type held: “Write Lock (unique_lock)”
  • Can other threads acquire a “Read” lock: “Denied”
  • Can other threads acquire a “Write” lock: “Denied”
  • Explanation: Write operations require exclusive access
How Does C++ Read-Write Lock (shared_mutex) Work?

Conclusion

Therefore, the core value of <span>shared_mutex</span> is

“When reads far exceed writes, it allows concurrent reads while ensuring safe writes.”

Next time you encounter a scenario with many reads and few writes, try using <span>shared_mutex</span>!

Leave a Comment