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