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

Iterating safely over a `std::map` in multithreaded code can be challenging, as modifications to the map while iterating can lead to undefined behavior. To ensure safety, one approach is to use mutexes to lock the map during iteration. This prevents other threads from modifying the map while it is being accessed. Another method is to use copy-on-write strategies or to maintain a snapshot of the map for reading purposes.

Here’s an example of how to iterate safely using mutexes:

#include <map> #include <mutex> #include <thread> #include <iostream> std::map myMap; std::mutex mapMutex; void modifyMap() { std::lock_guard<:mutex> lock(mapMutex); myMap[1] = "First Entry"; myMap[2] = "Second Entry"; } void readMap() { std::lock_guard<:mutex> lock(mapMutex); for (const auto& pair : myMap) { std::cout << pair.first << ": " << pair.second << std::endl; } } int main() { std::thread t1(modifyMap); std::thread t2(readMap); t1.join(); t2.join(); return 0; }

C++ std::map multithreading mutex safe iteration thread safety