std::shared_lock<Mutex>::lock (3) - Linux Manuals
std::shared_lock<Mutex>::lock - std::shared_lock<Mutex>::lock
void lock(); (since C++14)
Locks the associated mutex in shared mode. Effectively calls mutex()->lock_shared().
* Any exceptions thrown by mutex()->lock_shared()
* If there is no associated mutex, std::system_error with an error code of std::errc::operation_not_permitted
* If the associated mutex is already locked by this shared_lock (that is, owns_lock returns true), std::system_error with an error code of std::errc::resource_deadlock_would_occur
This section is incomplete
Reason: show a meaningful use of shared_lock::lock
// Run this code
std::string file = "Original content."; // Simulates a file
std::mutex output_mutex; // mutex that protects output operations.
std::shared_mutex file_mutex; // reader/writer mutex
void read(int id)
std::shared_lock lock(file_mutex, std::defer_lock); // Do not lock it first.
lock.lock(); // Lock it here.
content = file;
std::cout << "Contents read by reader #" << id << ": " << content << '\n';
file = "New content";
std::cout << "New content saved.\n";
std::cout << "Two readers reading from file.\n"
<< "A writer competes with them.\n";
std::thread reader1(read, 1);
std::thread reader2(read, 2);
std::cout << "The first few operations to file are done.\n";
reader1 = std::thread(read, 3);
Two readers reading from file.
A writer competes with them.
Contents read by reader #1: Original content.
Contents read by reader #2: Original content.
New content saved.
The first few operations to file are done.
Contents read by reader #3: New content
tries to lock the associated mutex
try_lock (public member function)
unlocks the associated mutex
unlock (public member function)