Table of Contents

<shared_mutex>

<shared_mutex> provides std::shared_mutex for reader-writer synchronization: multiple readers can hold the lock simultaneously, but a single writer has exclusive access. Use std::shared_lock<shared_mutex> for readers and std::unique_lock<shared_mutex> for writers.

Use it when you have many readers and few writers; otherwise std::mutex is simpler.

Example

This example demonstrates reader-writer locking where two reader threads can access data simultaneously but a writer has exclusive access.

// compile: g++ -std=c++17 -pthread -o sharedmutexexample sharedmutexexample.cpp
// run: ./sharedmutexexample
// description: multiple readers, exclusive writer
 
#include <shared_mutex>
#include <thread>
#include <iostream>
 
std::shared_mutex data_lock;
int data = 0;
 
void reader(int id) {
    std::shared_lock<std::shared_mutex> lock(data_lock);
    std::cout << "reader " << id << ": data = " << data << "\n";
}
 
void writer() {
    std::unique_lock<std::shared_mutex> lock(data_lock);
    data++;
    std::cout << "writer: updated to " << data << "\n";
}
 
int main() {
    std::thread r1(reader, 1);
    std::thread r2(reader, 2);
    std::thread w(writer);
 
    r1.join();
    r2.join();
    w.join();
 
    return 0;
}