How do I reserve capacity ahead of time with std::vector in multithreaded code?

Learn how to efficiently reserve capacity for `std::vector` in C++ when working with multithreaded applications. This technique reduces memory fragmentation and improves performance by ensuring that the required memory is pre-allocated.
std::vector, C++, multithreading, memory management, performance optimization

#include <iostream>
#include <vector>
#include <thread>

void fill_vector(std::vector<int>& vec, int size) {
    vec.reserve(size); // Reserve memory ahead of time
    for (int i = 0; i < size; ++i) {
        vec.push_back(i);
    }
}

int main() {
    const int size = 1000000;
    std::vector<int> vec;

    // Launch multiple threads to fill the vector
    std::thread t1(fill_vector, std::ref(vec), size);
    std::thread t2(fill_vector, std::ref(vec), size);

    t1.join();
    t2.join();

    std::cout << "Vector size: " << vec.size() << std::endl;
    return 0;
}
    

std::vector C++ multithreading memory management performance optimization