Erasing elements from a `std::deque` while iterating through it in a multithreaded environment requires caution to avoid undefined behavior. You can use iterators to keep track of the current position in the deque, but you must ensure that no other threads are modifying the deque at the same time. The C++ Standard Library provides mechanisms to manage concurrency, but it's essential to synchronize access to shared data.
#include <iostream>
#include <deque>
#include <thread>
#include <mutex>
std::mutex mtx; // Mutex for synchronization
std::deque<int> myDeque;
void workerThread() {
for (int i = 0; i < 10; ++i) {
std::lock_guard<std::mutex> lock(mtx);
myDeque.push_back(i);
}
}
void eraseElements() {
std::lock_guard<std::mutex> lock(mtx);
for (auto it = myDeque.begin(); it != myDeque.end();) {
if (*it % 2 == 0) { // Erase even numbers
it = myDeque.erase(it); // Erase returns the next iterator
} else {
++it; // Only increment if not erasing
}
}
}
int main() {
std::thread t1(workerThread);
std::thread t2(eraseElements);
t1.join();
t2.join();
std::lock_guard<std::mutex> lock(mtx);
for (const auto &elem : myDeque) {
std::cout << elem << " ";
}
std::cout << 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 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?