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

Iterating safely over a std::set in multithreaded C++ code requires careful management of locks to prevent data races and undefined behavior. Since std::set is not thread-safe by default, you need to ensure that no other thread modifies the set while you are iterating over it. This can be achieved using locks, such as std::mutex, to synchronize access.

Here’s how you can safely iterate over a std::set while allowing other threads to modify it:

#include <iostream> #include <set> #include <thread> #include <mutex> std::set<int> mySet; std::mutex myMutex; void addElement(int value) { std::lock_guard<std::mutex> lock(myMutex); mySet.insert(value); } void iterateSet() { std::lock_guard<std::mutex> lock(myMutex); for (const auto &element : mySet) { std::cout << element << std::endl; } } int main() { std::thread t1(addElement, 1); std::thread t2(addElement, 2); std::thread t3(iterateSet); t1.join(); t2.join(); t3.join(); return 0; }

C++ std::set multithreaded iteration locks std::mutex