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.
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.
#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;
}
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?