How do I provide stable iteration order with std::deque in multithreaded code?

In multithreaded applications, ensuring stable iteration order while using std::deque can be challenging due to concurrent modifications. Here’s how you can handle this problem effectively.

Using Mutex for Synchronization

The main strategy is to use a mutex to synchronize access to the std::deque. This approach prevents data races and ensures that the queue's state does not change unexpectedly while it is being iterated over.

Example Code

#include <iostream> #include <deque> #include <thread> #include <mutex> #include <chrono> std::deque data; std::mutex mtx; void producer() { for (int i = 0; i < 10; ++i) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); std::lock_guard<std::mutex> lock(mtx); data.push_back(i); std::cout << "Produced: " << i << std::endl; } } void consumer() { for (int i = 0; i < 10; ++i) { std::this_thread::sleep_for(std::chrono::milliseconds(150)); std::lock_guard<std::mutex> lock(mtx); if (!data.empty()) { int value = data.front(); data.pop_front(); std::cout << "Consumed: " << value << std::endl; } } } int main() { std::thread t1(producer); std::thread t2(consumer); t1.join(); t2.join(); return 0; }

C++ std::deque multithreading synchronization mutex