How do I iterate safely under modification with std::unordered_map in multithreaded code?

In C++, when working with a multithreaded application that modifies an std::unordered_map, you must ensure that you handle simultaneous reads and writes safely to avoid data races and undefined behavior. The best approach involves using synchronization primitives such as mutexes to protect the data structure while it is being accessed or modified.

Here’s a basic example of how to safely iterate over an std::unordered_map while allowing concurrent modifications:

#include #include #include #include #include std::unordered_map myMap; std::mutex mapMutex; void modifyMap(int key, int value) { std::lock_guard<:mutex> lock(mapMutex); myMap[key] = value; // Simulate some work } void readMap() { std::lock_guard<:mutex> lock(mapMutex); for (const auto& pair : myMap) { std::cout << "Key: " << pair.first << ", Value: " << pair.second << std::endl; } } int main() { std::vector<:thread> threads; // Spawn threads to modify the map for (int i = 0; i < 10; ++i) { threads.push_back(std::thread(modifyMap, i, i * 100)); } // Spawn a thread to read the map threads.push_back(std::thread(readMap)); // Join threads for (auto& thread : threads) { thread.join(); } return 0; }

C++ std::unordered_map multithreading synchronization mutex