How do I erase elements while iterating with std::unordered_map in multithreaded code?

Erasing elements from an `std::unordered_map` while iterating over it in multithreaded code can lead to undefined behavior if not handled properly. When one thread modifies the map (e.g., erasing an element), while another thread is iterating over it, it can result in race conditions. To safely remove elements during iteration, you can use techniques such as locking, iterators, or copying the keys to erase in a separate step. Here's an example of how to safely do this using a mutex for synchronization:

#include <iostream> #include <unordered_map> #include <thread> #include <mutex> std::unordered_map<int, std::string> myMap; std::mutex mapMutex; void eraseFunction() { std::lock_guard<std::mutex> lock(mapMutex); for (auto it = myMap.begin(); it != myMap.end();) { if (it->first % 2 == 0) { // Example condition to erase element it = myMap.erase(it); // Erase and get the next iterator } else { ++it; // Only increment if not erasing } } } void insertFunction(int key, const std::string& value) { std::lock_guard<std::mutex> lock(mapMutex); myMap[key] = value; // Safely insert new elements } int main() { // Populate the unordered_map for (int i = 0; i < 10; ++i) { insertFunction(i, "Value " + std::to_string(i)); } // Start a thread to erase elements std::thread t1(eraseFunction); t1.join(); // Wait for thread to finish // Output remaining elements for (const auto& pair : myMap) { std::cout << pair.first << ": " << pair.second << std::endl; } return 0; }

C++ std::unordered_map multithreading erase elements iterator safety mutex