Skip to content

Instantly share code, notes, and snippets.

@selfboot
Created January 10, 2025 09:47
Show Gist options
  • Save selfboot/dc0d9450ded391bc28a43aecd1045694 to your computer and use it in GitHub Desktop.
Save selfboot/dc0d9450ded391bc28a43aecd1045694 to your computer and use it in GitHub Desktop.
A simple example demonstrating the coredump problem
#include <iostream>
#include <thread>
#include <unordered_map>
#include <shared_mutex>
#include <vector>
#include <random>
class DataManager {
private:
std::shared_mutex mutex_;
std::unordered_map<std::string, std::string> m_data;
public:
int num_keys = 100;
void loadData() {
std::unordered_map<std::string, std::string> localdata;
std::vector<std::string> 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<std::shared_mutex> lock(mutex_);
m_data.swap(localdata);
}
}
std::string readData(const std::string& key) {
{
std::shared_lock<std::shared_mutex> 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<std::thread> 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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment