skip to content

For a read-mostly C++ stock catalog, how do std::shared_mutex and std::shared_lock work, and when do they fail to pay off?

level: middleimportance: should knowfreq 48%

answer

  1. many readers or one writer
  2. lock_shared for readers
  3. no upgrade from shared to exclusive
  4. priority left to the implementation
  5. short reads favour a plain mutex

basics

~20 s

std::shared_mutex (C++17) lets many threads hold shared ownership for reading while exclusive ownership excludes everyone. Readers lock through std::shared_lock, writers through std::unique_lock or lock_guard. It pays off when read sections are long and contended enough to outweigh its higher per-acquisition cost.

solid answer

~40 s

`std::shared_mutex` has two ownership modes: exclusive (`lock`, `try_lock`, `unlock`) and shared (`lock_shared`, `try_lock_shared`, `unlock_shared`). Any number of threads may share it, at least 10000 by the standard, but never while one holds it exclusively. In the stock catalog, `units()` takes `std::shared_lock lock(mu_);` (the RAII wrapper for shared mode, C++14) and `restock()` takes `std::unique_lock` or `std::lock_guard`. Declare the mutex `mutable` so `const` readers can lock it. There is no upgrade: a reader that decides to write must release and take an exclusive lock, then re-check, because the data may have changed. Re-acquiring any ownership a thread already holds is undefined behaviour. The standard says nothing about reader or writer priority. Each acquisition costs more than a `std::mutex`, so for short reads a plain mutex is often faster; measure first.

code

cpp · 30 lines
cpp
#include <iostream>
#include <map>
#include <mutex>
#include <shared_mutex>
#include <string>
#include <thread>
#include <vector>
class StockCatalog {
    mutable std::shared_mutex mu_;
    std::map<std::string, int> units_;
public:
    int units(const std::string& sku) const {
        std::shared_lock lock(mu_);          // many readers at once
        auto it = units_.find(sku);
        return it == units_.end() ? 0 : it->second;
    }
    void restock(const std::string& sku, int qty) {
        std::unique_lock lock(mu_);          // one writer, no readers
        units_[sku] += qty;
    }
};
int main() {
    StockCatalog catalog;
    std::vector<std::thread> threads;
    for (int i = 0; i < 4; ++i)
        threads.emplace_back([&] { for (int n = 0; n < 1000; ++n) catalog.units("bolt-m8"); });
    threads.emplace_back([&] { for (int n = 0; n < 100; ++n) catalog.restock("bolt-m8", 1); });
    for (auto& t : threads) t.join();
    std::cout << "bolt-m8: " << catalog.units("bolt-m8") << '\n';
}

go deeper

for a junior

Know that a shared_mutex lets many readers in together but only one writer, with shared_lock for reading.

for a middle

Explain the two ownership modes, the RAII type for each, mutable on the mutex and why there is no upgrade.

for a senior

Catch the check-then-upgrade race, recursive shared locking and a reader-side cache write, and benchmark before adopting.

for a principal

Decide between reader-writer locks, sharding and immutable snapshots for a read-mostly service.

## Two ownership modes A `std::mutex` admits one thread at a time, even if every thread only reads. `std::shared_mutex` (C++17, header `<shared_mutex>`) adds a second mode: - **Exclusive ownership** through `lock()`, `try_lock()` and `unlock()`: one thread, nobody else in either mode. - **Shared ownership** through `lock_shared()`, `try_lock_shared()` and `unlock_shared()`: many threads at once, as long as no thread holds exclusive ownership. The maximum number of sharers is unspecified but at least 10000. `std::shared_timed_mutex` (C++14) is the same with timed members; the standard even permits `shared_mutex` to be a synonym for it. ## The RAII types | Who | Lock type | Mode | |---|---|---| | reader | `std::shared_lock<std::shared_mutex>` (C++14) | shared | | writer | `std::unique_lock<std::shared_mutex>` or `std::lock_guard` | exclusive | `std::shared_lock` mirrors `std::unique_lock`: it accepts `std::defer_lock`, `std::try_to_lock` and `std::adopt_lock`, has `unlock()` and `release()`, and is movable, but it calls the `*_shared` members. In the warehouse catalog the read path is a `const` member function, so the mutex is declared `mutable`; locking is not a change to the catalog's observable state. ## Writing the read path A shared lock protects the data only while it is held, so the reader must **copy out** what it needs before the lock goes away: ```cpp int units(const std::string& sku) const { std::shared_lock lock(mu_); auto it = units_.find(sku); return it == units_.end() ? 0 : it->second; // copy, not a reference } ``` Returning `const int&` into the map, or an iterator, would let the caller read the element after `restock()` has started rewriting the map under an exclusive lock. Keep the shared section to the lookup and the copy; formatting, logging and network calls go after it. A `std::shared_lock` built with `std::defer_lock` and locked later, or a timed `shared_lock` on a `std::shared_timed_mutex`, works the same way as its `unique_lock` counterpart. ## Rules that bite 1. **No upgrade.** `shared_mutex` has no member that turns shared ownership into exclusive ownership. A reader that discovers it must write has to drop the shared lock, take the exclusive lock, and **re-check** the condition, because another writer may have run in between. Doing the check once under the shared lock and writing later is a time-of-check to time-of-use bug. 2. **No recursion in either mode.** The standard makes it undefined behaviour for a thread to attempt to recursively gain any ownership of a `shared_mutex`, so a reader that calls another reading member function on the same object while holding the shared lock is already in trouble. 3. **Priority is unspecified.** Whether a waiting writer blocks newly arriving readers, or a stream of readers can starve a writer, is left to the implementation. Do not design around one library's policy. 4. **Data race rules still apply.** Shared ownership is for reading only. A `mutable` cache updated inside a reader's shared section is a data race between readers. ## When it does not pay off Shared locking keeps a reader count that every reader updates, so each acquisition typically costs as much as locking a plain mutex, often more, and the count's cache line bounces between cores. The pay-off appears only when: - reads vastly outnumber writes, - each read section is long enough that letting readers overlap saves real time, and - there is actual contention. For a `std::map` lookup of a few hundred nanoseconds a plain `std::mutex` is frequently as fast or faster. The engineering answer is to measure the real workload with both. Alternatives worth naming in the same breath: sharding the catalog across several mutexes, or publishing immutable snapshots that readers access without locking at all. ## Checklist - `mutable std::shared_mutex` beside the data it protects. - Readers use `std::shared_lock`; writers use `std::unique_lock` or `std::lock_guard`. - No upgrade attempts; release, relock exclusively, re-check. - No nested locking of the same `shared_mutex` in either mode. - A benchmark against a plain `std::mutex` before keeping it.

  • How do you turn a shared lock into an exclusive one when a reader decides it must update the catalog?
    You cannot upgrade in place: `std::shared_mutex` has no upgrade operation. Release the `std::shared_lock`, take a `std::unique_lock` on the same mutex, and re-check the condition that made you want to write, because another writer may have changed the data in the gap. Waiting for the exclusive lock while still holding the shared one would deadlock.
  • Can a stream of readers starve a writer on std::shared_mutex?
    The standard does not say. It specifies the two ownership modes and their exclusion rules, but leaves reader and writer priority to the implementation. Some implementations stop admitting new readers once a writer is waiting; code that depends on either policy is not portable.

  • std::shared_mutex is always faster than std::mutex for read-heavy code.
  • A shared_lock can be upgraded to exclusive without releasing it.
  • The standard guarantees writers are never starved by readers.
  • A reader may take the same shared_mutex again in a nested call.
  • Readers may update a mutable cache while holding only the shared lock.