Vector filling across OpenMP threads
<p>I have an algorithm for which one goal is to fill vectors. For the sake of performance, iterations of the algorithm are spread across OpenMP threads. I was wondering which way would provide the better/safer way of filling the vectors.</p>

<p>Note that the ordering of the vectors must be consistent (i.e. value n of vec1 must come from the same iteration than value n of vec2.)</p>

<p><strong>Hypothesis 1:</strong></p>

<pre><code>std::vector&lt;BasicType&gt; vec1;
std::vector&lt;BasicType&gt; vec2;
#pragma opm parallel for
for(...)
{
    // Do some intensive stuff to compute val1 and val2
    // ...

    #pragma omp critical
    {
        vec1.push_back(val1);
        vec2.push_back(val2);
    }
}
// Then go on to work with vec1 and vec2...
</code></pre>

<p><strong>Hypothesis 2:</strong></p>

<pre><code>std::vector&lt;BasicType&gt; vec1;
std::vector&lt;BasicType&gt; vec2;
#pragma opm parallel
{
    std::vector&lt;BasicType&gt; vec1local;
    std::vector&lt;BasicType&gt; vec2local;
    #pragma omp for
    for(...)
    {
        // Do some intensive stuff to compute val1 and val2
        // ...

        vec1local.push_back(val1);
        vec2local.push_back(val2);
    }

    #pragma omp critical
    {
        // See note 1 below
        vec1.insert(vec1.end(), vec1local.begin(), vec1local.end());
        vec2.insert(vec2.end(), vec2local.begin(), vec2local.end());
    }
}
// Then go on to work with vec1 and vec2...
</code></pre>

<p><em>Note 1:</em> This was taken from <a href="https://stackoverflow.com/questions/18147400/best-way-to-append-vector-to-vector">Best way to append vector to vector</a></p>

<p><em>Note 2:</em> It seems val1 and val2 could be combined in some object in order to maintain consistency and work only with one vector, but for now it seems inpractical for the remainder of the algorithm.</p>

<p><em>Note 3:</em> To give an order of magnitude, the <code>for</code> loop contains around 100 iterations splitted among 4 threads. Apart for very few exceptions, each iteration is expected to have the same workload (which brings the issue of the critical sections happening around the same time.)</p>

<p><em>Note 4:</em> Just for the records, the whole thing deals with image stabilisation, and runs on a Tegra K1 architecture. Compiler used is gcc 4.8.4.</p>