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;
}
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 erase elements while iterating with std::unordered_map in multithreaded code?
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?