title: How to use an OpenMP Barrier
body: <p>I want to make sure I implement a barrier correctly. Right now, amStaticThreaded starts a ton of new threads every time it is called. In my main routine, everything after amStaticThreaded can be done by only one thread, but that part is extremely fast. Is there a better way than to have amStaticThreaded start a new set of threads every time</p>
  
  <p>I have the following setup in my code:</p>
  
  <pre><code>void amStaticThreaded(int nshocks, int nstates,
                        MatrixXd&amp; valmat, MatrixXd&amp; EV_prev, MatrixXd&amp; fullmat) {
  
    #pragma omp parallel for
    for(int i = 0; i &lt; nshocks; i++) {
  
      // this does the add part    
      RowVectorXd vrow(nstates);
      vrow = EV_prev.row(i);
  
      fullmat.middleRows( i*nstates, nstates).rowwise() += vrow;
      valmat.row(i)   = fullmat.middleRows(i*nstates, nstates).rowwise().maxCoeff().transpose();
  
    }
  
  }
  
  int main() {
  
    // ...
  
    // ITERATION ON CONTINUATION VALUE  
    cout &lt;&lt; "entering loop" &lt;&lt; endl;
    while ( (err &gt; TOL) &amp;&amp; (itercount &lt; MAXIT)) {
  
      // GET NEW EXPECTED VALUE FUNCTION
      EV_prev = (T_BIG * V_prev);
      EV_prev.array() *= beta;
  
      fullmat = staticmat;
      amStaticThreaded(Nshocks, nstates, V_new, EV_prev, fullmat);
  
      // THERE SHOULD BE A BARRIER HERE
  
      // FIGURE OUT THE ERROR BOUNDS
      mmdiff = (V_new.array() - V_prev.array());
      lbound = beta * double(mmdiff.minCoeff());
      ubound = beta * double(mmdiff.maxCoeff());
  
      // POSSIBLY ADJUST THE VALUE FUNCTION
      relres = ubound - lbound;
      if(relres &lt; TOL) {
        V_new.array() += (ubound + lbound)/2.0;
      }
      err = relres;
  
      // UPDATE ITER COUNT AND VALUE FUNCTION
      cout &lt;&lt; "i: " &lt;&lt; itercount &lt;&lt; ": " &lt;&lt; err &lt;&lt; endl;
      itercount++;
      V_prev = V_new;
    } // end while
    cout &lt;&lt; "DONE with iteration!" &lt;&lt; endl;
  }
  </code></pre>