omp parallel for : How to make threads write to private arrays and merge all the arrays once all the threads finished processing
<p>I have a requirement to calculate <code>z</code> values, push them into arrays <code>B</code> and <code>s2</code>.</p>

<p>I tried to parallelize the processing using <code>omp parallel for</code>.</p>

<p>One problem I see is, If I don't put <code>B[i][j] += z</code> and <code>s2[i] += z</code> statements in <code>critical</code> section, I see lot of <code>NaN</code> values being generated.</p>

<p>Just wondering if there is a way to write the <code>z</code> values to separate arrays (one array per thread) and merge them at the end.</p>

<p>Any help is greatly appreciated.</p>

<pre><code>#pragma omp parallel
{
    double z;
    #pragma omp parallel for
    for(int t=1; t&lt;n; t++) {
        double phi_i[N];
        double obs_j_seq_t[N];

        for(int i=0; i&lt;N; i++) {
            for(int j=0; j&lt;N; j++) {
                z=phi_i[i]*trans[i*N + j]*obs_j_seq_t[j]*beta[t*N+j]/c[t]; 
                #pragma omp critical
                { 
                    B[i][j] += z;
                    s2[i] += z;
                }
            }
        }
    }
}
</code></pre>