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

In C++, when working with a `std::set` in a multithreaded environment, it is crucial to ensure thread safety. Unlike other containers, `std::set` provides an ordered collection of unique elements, but directly modifying it while iterating can lead to undefined behavior. To safely erase elements from a `std::set` while iterating, you can use an iterator that allows for safe modifications.

This example demonstrates how to remove elements from a `std::set` while iterating over it, using access to mutexes to manage thread safety properly.

// Example code for erasing elements from std::set in a multithreaded context #include #include #include #include std::set mySet = {1, 2, 3, 4, 5}; std::mutex mtx; void eraseElements(int valueToErase) { std::lock_guard<:mutex> lock(mtx); for (auto it = mySet.begin(); it != mySet.end(); ) { if (*it == valueToErase) { it = mySet.erase(it); // Erase and move to the next valid iterator } else { ++it; // Move to the next element } } } int main() { std::thread t1(eraseElements, 3); std::thread t2(eraseElements, 5); t1.join(); t2.join(); for (int num : mySet) { std::cout << num << " "; } return 0; }

C++ std::set multithreaded thread safety erase elements