#include <iostream>
#include <unordered_map>
#include <shared_mutex>
#include <thread>
#include <vector>
class ThreadSafeCache {
private:
mutable std::shared_mutex mutex_;
std::unordered_map<int, std::string> cache_;
public:
std::string get(int key) const {
std::shared_lock lock(mutex_);
auto it = cache_.find(key);
if (it != cache_.end()) {
return it->second;
}
return "Not found";
}
void set(int key, const std::string& value) {
std::unique_lock lock(mutex_);
cache_[key] = value;
}
};
int main() {
ThreadSafeCache cache;
auto reader = [&cache](int id) {
for (int i = 0; i < 5; ++i) {
std::cout << "Reader " << id << " gets: " << cache.get(i % 3) << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(50));
}
};
auto writer = [&cache](int id) {
for (int i = 0; i < 3; ++i) {
cache.set(i, "Value " + std::to_string(id) + "-" + std::to_string(i));
std::cout << "Writer " << id << " set value for key " << i << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
};
std::vector<std::thread> threads;
for (int i = 0; i < 3; ++i) {
threads.emplace_back(writer, i);
}
for (int i = 0; i < 5; ++i) {
threads.emplace_back(reader, i);
}
for (auto& t : threads) {
t.join();
}
return 0;
}