skip to content
Ivan's wiki
Site Tools
Search
Tools
Show pagesource
Backlinks
Recent Changes
Media Manager
Sitemap
>
Recent Changes
Media Manager
Sitemap
hpp-shared-mutex
This page is read only. You can view the source, but not change it.
# <shared_mutex> **[<shared_mutex>](https://en.cppreference.com/w/cpp/header/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. This example demonstrates reader-writer locking where two reader threads can access data simultaneously but a writer has exclusive access. ```cpp // 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; } ```
Page Tools
Show pagesource
Backlinks
Back to top