#include #include #include #include #include #include class DataManager { private: std::shared_mutex mutex_; std::unordered_map m_data; public: int num_keys = 100; void loadData() { std::unordered_map localdata; std::vector keys; for(int i = 0; i < num_keys; i++) { keys.push_back("test" + std::to_string(i)); } for(int i = 0; i < num_keys; i++) { localdata[keys[i]] = "test" + std::to_string(i); } { std::unique_lock lock(mutex_); m_data.swap(localdata); } } std::string readData(const std::string& key) { { std::shared_lock lock(mutex_); return m_data[key]; } return 0; } }; void readerThread(DataManager& dm, int id) { while (true) { int key = rand() % dm.num_keys + dm.num_keys / 2; std::string key_str = "test" + std::to_string(key); std::string result = dm.readData(key_str); } } void loaderThread(DataManager& dm) { while (true) { dm.loadData(); } } int main() { DataManager dm; std::thread loader(loaderThread, std::ref(dm)); std::vector readers; for (int i = 0; i < 4; i++) { readers.emplace_back(readerThread, std::ref(dm), i); } loader.join(); for (auto& t : readers) { t.join(); } return 0; }