I want to understand advantage of std::shared_mutex
. I read that the main feature is that we can have several thread-readers and single thread-writer
My code
#include <iostream>
#include <vector>
#include <mutex>
#include <shared_mutex>
#include <optional>
#include <string>
#include <thread>
using namespace std;
class NotesManager {
public:
optional<string> getValue(size_t index) const {
shared_lock<shared_mutex> sharedLock(mutex_);
//unique_lock<shared_mutex> uniqueLock(mutex_);
if (index < notes_.size()) {
return notes_[index];
}
return std::nullopt;
}
void pushBack(const string& newNote) {
unique_lock<shared_mutex> uniqueLock(mutex_);
notes_.push_back(newNote);
}
private:
vector<string> notes_;
mutable shared_mutex mutex_;
};
int main() {
NotesManager mgr;
vector<thread> threads;
for (int i = 0; i < 20000; ++i) {
if (i % 2 == 0) {
threads.emplace_back([i, &mgr]() {
const auto curr = std::to_string(i);
mgr.pushBack(curr);
});
} else {
threads.emplace_back([i, &mgr]() {
mgr.getValue(i);
});
threads.emplace_back([i, &mgr]() {
const auto curr = std::to_string(i);
mgr.pushBack(curr);
});
}
}
for (auto& t : threads) {
t.join();
}
}
I tested the code with shared_lock<shared_mutex>
– resulat is
./lock_example 0.12s user 4.60s system 138% cpu 3.412 total
And the second test – replaced shared_lock with unique_lock — EVEN FASTER:
./lock_example 0.12s user 4.18s system 126% cpu 3.390 total
The results are almost the same
Is it possible to modify my example to show advantage of shared_lock
?
2