How do I iterate safely under modification with std::deque in multithreaded code?

Iterating over a `std::deque` in a multithreaded environment while handling modifications can be challenging due to potential data races. To ensure safety, it's crucial to implement proper synchronization mechanisms like mutexes to protect the data structure while iterating.

Below is an example of how to safely iterate over a `std::deque` while allowing modifications from other threads:

#include #include #include #include #include std::deque myDeque; std::mutex dequeMutex; void modifyDeque() { for (int i = 0; i < 5; ++i) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); std::lock_guard<:mutex> lock(dequeMutex); myDeque.push_back(i); std::cout << "Added: " << i << std::endl; } } void iterateDeque() { std::lock_guard<:mutex> lock(dequeMutex); for (const auto& item : myDeque) { std::cout << "Item: " << item << std::endl; } } int main() { std::thread t1(modifyDeque); std::thread t2(iterateDeque); t1.join(); t2.join(); return 0; }

C++ std::deque multithreading iteration synchronization mutex thread safety