#include <iostream>
#include <thread>
#include <shared_mutex>
#include <vector>
#include <chrono>
class ThreadSafeCounter {
private:
mutable std::shared_mutex mutex_;
int value_ = 0;
public:
int get() const {
std::shared_lock lock(mutex_);
return value_;
}
void increment() {
std::unique_lock lock(mutex_);
value_++;
}
};
int main() {
ThreadSafeCounter counter;
auto reader = [&counter](int id) {
for (int i = 0; i < 3; ++i) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
std::cout << "Reader " << id << " sees value " << counter.get() << std::endl;
}
};
auto writer = [&counter]() {
for (int i = 0; i < 3; ++i) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
counter.increment();
std::cout << "Writer incremented value\n";
}
};
std::vector<std::thread> threads;
threads.emplace_back(writer);
for (int i = 0; i < 3; ++i) {
threads.emplace_back(reader, i);
}
for (auto& t : threads) {
t.join();
}
return 0;
}