C++
threading
std::shared_mutex
thread starvation
concurrency

Can thread trying to stdlock_unique an stdshared_mutex be starved by threads calling stdlock_shared?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Yes, a thread waiting for exclusive access on std::shared_mutex can be starved by a steady stream of readers. The C++ standard specifies the locking interface, but it does not require a fairness policy that guarantees waiting writers will eventually win.

What std::shared_mutex Guarantees

A std::shared_mutex supports two modes:

  • shared ownership for readers
  • exclusive ownership for writers

Multiple threads may hold a shared lock at the same time, but only one thread may hold the exclusive lock. What the standard does not promise is reader priority, writer priority, or FIFO ordering. That part is implementation-defined.

Because fairness is unspecified, two standard library implementations can behave differently under load. One may favor throughput for readers. Another may block new readers once a writer is queued. Portable code cannot assume either policy.

Why Starvation Happens

Writer starvation occurs when readers keep arriving quickly enough that the mutex never becomes fully free for an exclusive lock. If the implementation allows new shared acquisitions while a writer is already waiting, the writer can remain blocked for an unbounded amount of time.

That means the answer to the original question is not just theoretical. It is a real risk in read-heavy systems.

cpp
1#include <chrono>
2#include <iostream>
3#include <shared_mutex>
4#include <thread>
5#include <vector>
6
7std::shared_mutex mutex_;
8int value = 0;
9
10void reader() {
11    for (int i = 0; i < 100000; ++i) {
12        std::shared_lock lock(mutex_);
13        int snapshot = value;
14        (void)snapshot;
15    }
16}
17
18void writer() {
19    std::unique_lock lock(mutex_);
20    ++value;
21    std::cout << "writer acquired lock\n";
22}

If enough reader threads repeatedly take and release the shared lock, the writer may wait much longer than expected. Whether it waits forever in practice depends on timing and the library implementation.

What the Standard Leaves Open

This is an important concurrency lesson: an API can define safety without defining fairness. std::shared_mutex prevents invalid simultaneous write access, but it does not guarantee balanced scheduling between readers and writers.

So if your design depends on writer progress, relying on default fairness is weak engineering. You need a stronger policy at a higher level.

Practical Mitigations

The first mitigation is to keep read-side critical sections short. Long-lived shared locks make starvation easier.

The second mitigation is to stop admitting new readers once a writer announces intent. You can implement that with an extra mutex, atomic flag, or condition variable around the shared mutex.

cpp
1#include <atomic>
2#include <mutex>
3#include <shared_mutex>
4
5std::shared_mutex data_mutex;
6std::mutex gate_mutex;
7std::atomic<bool> writer_waiting = false;
8
9void safe_read() {
10    for (;;) {
11        while (writer_waiting.load(std::memory_order_acquire)) {
12        }
13
14        std::shared_lock lock(data_mutex);
15        if (!writer_waiting.load(std::memory_order_acquire)) {
16            break;
17        }
18    }
19}
20
21void safe_write() {
22    std::lock_guard gate(gate_mutex);
23    writer_waiting.store(true, std::memory_order_release);
24    std::unique_lock lock(data_mutex);
25    writer_waiting.store(false, std::memory_order_release);
26}

This pattern is simplified, but the idea is clear: once a writer is pending, new readers should stop cutting in line.

When Another Primitive Is Better

If write latency matters, a plain std::mutex may outperform a reader-writer lock in real systems, especially when read sections are tiny. Reader-writer locks only help when concurrent reads are common and meaningful.

Some platforms also provide synchronization primitives with explicit fairness or writer preference. If starvation is a correctness issue rather than just a performance concern, choose a primitive that documents the policy you need.

Common Pitfalls

A common mistake is assuming that "eventually" is guaranteed because readers release their locks quickly. Concurrency libraries do not owe you fairness unless they say so.

Another mistake is benchmarking only average throughput. A system can look fast while still having terrible worst-case write latency.

Finally, avoid building logic that depends on implementation-specific behavior of one standard library. That often breaks when the code moves to a different compiler or operating system.

Summary

  • A writer waiting on std::shared_mutex can be starved by readers.
  • The standard does not guarantee fairness for std::shared_mutex.
  • Behavior depends on the library implementation and workload.
  • Keep shared critical sections short and consider blocking new readers when a writer is queued.
  • If writer progress matters, use a design or primitive with an explicit fairness policy.

Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Basis Lab
No course covers this one yet

Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.

Build my course
Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions