Skip to content
Tutorials Center
My learning

Topics

C++ Reference ยท Concurrency

C++ std::shared_mutex class

Reference for std::shared_mutex and std::shared_lock (C++17): let many readers run together while writers get exclusive access, with examples and pitfalls.

std::shared_mutex (header <shared_mutex>, C++17) is a reader-writer lock. It has two modes. In shared mode any number of threads can hold the mutex at once, which suits code that only reads. In exclusive mode a single thread holds it and nobody else, reader or writer, may enter, which suits code that modifies the data.

Take shared ownership with std::shared_lock and exclusive ownership with std::unique_lock or std::lock_guard. A reader-writer lock only pays off when reads are much more common than writes and the read work takes real time; otherwise a plain std::mutex is faster.

C++
std::shared_mutex rw;
std::map<std::string, int> table;

int read(const std::string& k) {
    std::shared_lock lock(rw);          // many readers at once
    return table.at(k);
}
void write(const std::string& k, int v) {
    std::unique_lock lock(rw);          // one writer, no readers
    table[k] = v;
}

Try it

C++ Readers share, writers exclude

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

C++ try_lock_shared shows the rules

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Syntax

C++
class shared_mutex {
public:
    shared_mutex();
    shared_mutex(const shared_mutex&) = delete;

    // exclusive ownership
    void lock();
    bool try_lock();
    void unlock();

    // shared ownership
    void lock_shared();
    bool try_lock_shared();
    void unlock_shared();
};

template<class Mutex> class shared_lock {
    explicit shared_lock(Mutex& m);
    shared_lock(Mutex& m, std::defer_lock_t) noexcept;
    shared_lock(Mutex& m, std::try_to_lock_t);
    shared_lock(Mutex& m, std::adopt_lock_t);
    // lock(), try_lock(), unlock(), owns_lock(), release(), swap()
};
Name Description
lock() / unlock() Exclusive mode. Blocks until no reader and no writer holds the mutex.
lock_shared() / unlock_shared() Shared mode. Blocks while a writer holds (or, in many implementations, is waiting for) the mutex.
try_lock() / try_lock_shared() Non-blocking attempts; return true on success. They may fail spuriously.
std::shared_lock RAII wrapper that calls lock_shared() and unlock_shared(). Movable, like unique_lock.

Returns: the try_ functions return bool; the others return nothing.

Errors / undefined behavior: a thread that already owns the mutex (in either mode) must not lock it again. Upgrading is not supported: holding a shared lock and then asking for an exclusive one on the same thread deadlocks. Unlocking a mode you do not hold is undefined.

Usage notes

  • Added in C++17 (shared_timed_mutex, with timeouts, in C++14). Both live in <shared_mutex>.
  • No upgrade or downgrade. To go from reading to writing, release the shared lock, take the exclusive lock, and re-check the condition, because another writer may have run in between.
  • Writer starvation: the standard does not say whether new readers may overtake a waiting writer. Implementations choose; do not depend on either behavior.
  • Readers must really only read. Mutating data under a shared lock is a data race. Mark reader functions const and the mutex mutable.
  • It is heavier than std::mutex. For tiny critical sections, the extra bookkeeping often makes a plain mutex faster, even with many readers.
  • Measure before choosing it. The right question is whether readers spend enough time inside the lock that running them in parallel matters.
  • Cache-line contention: every reader still updates the shared lock state, so scalability on many cores is limited.