#include <iostream>
#include <shared_mutex>
#include <thread>
#include <chrono>
class TimedResource {
private:
mutable std::shared_timed_mutex mutex_;
int value_ = 0;
public:
bool try_read(std::chrono::milliseconds timeout) const {
if (mutex_.try_lock_shared_for(timeout)) {
std::cout << "Read value: " << value_ << std::endl;
mutex_.unlock_shared();
return true;
}
return false;
}
bool try_write(int new_value, std::chrono::milliseconds timeout) {
if (mutex_.try_lock_for(timeout)) {
value_ = new_value;
std::cout << "Wrote value: " << value_ << std::endl;
mutex_.unlock();
return true;
}
return false;
}
};
int main() {
TimedResource resource;
auto reader = [&resource](int id) {
for (int i = 0; i < 3; ++i) {
if (resource.try_read(std::chrono::milliseconds(50))) {
std::cout << "Reader " << id << " succeeded\n";
} else {
std::cout << "Reader " << id << " timed out\n";
}
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
};
auto writer = [&resource](int id) {
for (int i = 0; i < 2; ++i) {
if (resource.try_write(id * 10 + i, std::chrono::milliseconds(200))) {
std::cout << "Writer " << id << " succeeded\n";
} else {
std::cout << "Writer " << id << " timed out\n";
}
std::this_thread::sleep_for(std::chrono::milliseconds(150));
}
};
std::vector<std::thread> threads;
threads.emplace_back(writer, 1);
threads.emplace_back(writer, 2);
for (int i = 0; i < 3; ++i) {
threads.emplace_back(reader, i);
}
for (auto& t : threads) {
t.join();
}
return 0;
}