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

Iterating safely over a std::vector in multithreaded code requires careful consideration to prevent data races and ensure consistency. In C++, utilizing mutexes or other synchronization mechanisms is essential when you modify a vector in one thread while iterating over it in another. Below is an example demonstrating how to safely iterate and modify a std::vector using a mutex for synchronization.

#include #include #include #include #include std::vector vec = {1, 2, 3, 4, 5}; std::mutex mtx; void modify_vector() { std::lock_guard<:mutex> lock(mtx); vec.push_back(6); vec.push_back(7); } void iterate_vector() { std::lock_guard<:mutex> lock(mtx); for(int v : vec) { std::cout << v << " "; } std::cout << std::endl; } int main() { std::thread t1(modify_vector); std::thread t2(iterate_vector); t1.join(); t2.join(); return 0; }

C++ std::vector multithreading safe iteration mutex