CodexBloom - Programming Q&A Platform

How to implement guide with thread safety when using std::unordered_map in c++11

👀 Views: 41 đŸ’Ŧ Answers: 1 📅 Created: 2025-05-31
c++11 multithreading unordered_map thread-safety cpp

I'm working with a question with thread safety while using `std::unordered_map` in my C++11 application. The map is being accessed and modified by multiple threads, and I'm seeing inconsistent results. For instance, when two threads try to insert elements simultaneously, I occasionally get a segmentation fault or corrupted data. I've implemented a simple producer-consumer model where one thread is inserting data while another is reading it. Here's a simplified version of my code: ```cpp #include <iostream> #include <unordered_map> #include <thread> #include <mutex> #include <chrono> std::unordered_map<int, std::string> myMap; std::mutex mapMutex; void producer(int id) { for (int i = 0; i < 10; ++i) { std::lock_guard<std::mutex> lock(mapMutex); myMap[i] = "Value " + std::to_string(i) + " from thread " + std::to_string(id); std::this_thread::sleep_for(std::chrono::milliseconds(10)); } } void consumer() { for (int i = 0; i < 10; ++i) { std::lock_guard<std::mutex> lock(mapMutex); if (myMap.find(i) != myMap.end()) { std::cout << myMap[i] << std::endl; } } } int main() { std::thread t1(producer, 1); std::thread t2(consumer); t1.join(); t2.join(); return 0; } ``` I ensured to protect the `unordered_map` with a `std::mutex`, but I'm still seeing issues. I also tried using `std::shared_mutex` with `std::unique_lock` for the consumer thread, but that didn't help either. The segmentation fault usually occurs during the insertion phase, and the output from the consumer is sometimes incomplete. I'm using GCC 9.3.0 on Ubuntu 20.04. Can anyone provide insight into potential pitfalls with this approach or suggest a better thread-safe design for accessing shared resources?