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

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;
}
    

C++ std::deque multithreading erase elements iterators synchronization