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;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?
How do I reserve capacity ahead of time with std::map for embedded targets?