std::shared_mutex Usage and Characteristics
- Nick Kuo
- Programming
- 28 Dec, 2023
std::shared_mutex is a reader contention aware lock.
When exclusive access is pending due to existing shared access, No more shared access can be acquired. This is the “draining” behavior.
#include <iostream>
#include <thread>
#include <shared_mutex>
using namespace std;
int main()
{
std::shared_mutex mutex;
cout << "Hello World" << endl;
int counter = 0;
std::thread t1([&]() {
while (true) {
cout << "BEGIN T1 acquire shared" << endl;
mutex.lock_shared();
cout << "DONE T1 acquire shared" << endl;
this_thread::sleep_for(chrono::seconds(5));
cout << "BEGIN T1 unlock shared" << endl;
mutex.unlock_shared();
cout << "DONE T1 unlock shared" << endl;
this_thread::sleep_for(chrono::seconds(5));
}
});
std::thread t2([&]() {
this_thread::sleep_for(chrono::milliseconds(2500));
while (true) {
cout << "BEGIN T2 acquire shared" << endl;
mutex.lock_shared();
cout << "DONE T2 acquire shared" << endl;
this_thread::sleep_for(chrono::seconds(5));
cout << "BEGIN T2 unlock shared" << endl;
mutex.unlock_shared();
cout << "DONE T2 unlock shared" << endl;
this_thread::sleep_for(chrono::seconds(5));
}
});
string input;
while (cin >> input) {
if (input == "1") {
cout << "BEGIN MAIN acquire exclusive" << endl;
mutex.lock();
cout << "END MAIN acquire exclusive" << endl;
}
else if (input == "2") {
cout << "BEGIN MAIN release exclusive" << endl;
mutex.unlock();
cout << "END MAIN release exclusive" << endl;
}
}
t1.join();
t2.join();
return 0;
}
Output:
Hello World
BEGIN T1 acquire shared
DONE T1 acquire shared
1
BEGIN MAIN acquire exclusive
BEGIN T2 acquire shared
BEGIN T1 unlock shared
DONE T1 unlock shared
END MAIN acquire exclusive
BEGIN T1 acquire shared