title: OpenMP synchronization within the loop
body: <p>I have a large loop that generates data. Each iteration takes, say, 1 second and produces a chunk of data. I need all chunks written into the file in the correct order.</p>
  
  <p>If I just wanted to parallelize the loop, I could write something like this (highly simplified):</p>
  
  <pre><code>    FILE* f = fopen("output.txt", "w");
      omp_lock_t lock;
      omp_init_lock(&amp;lock);
      int nIterations = 1000000;
  #pragma omp parallel for
      for(int thread=0; thread&lt;4; thread++)
      {
          int a=0, b=0, c=0;
          for(int n=thread; n&lt;nIterations; n+=4)
          {
              int value = do_computations(&amp;a, &amp;b, &amp;c);
              omp_set_lock(&amp;lock);
              fprintf(f, "%d\n", value);
              omp_unset_lock(&amp;lock);
          }
      }
  #pragma omp barrier
      fclose(f);
      omp_destroy_lock(&amp;lock);
  </code></pre>
  
  <p>This gets my output into the file, but the order of entries would not be guaranteed.</p>
  
  <p>I want to synchronize execution so that all threads do their tasks, then the master thread writes into the file, and then threads resume. In other words, I'd like something like this:</p>
  
  <pre><code>    #pragma omp parallel for
          for(int thread=0; thread&lt;4; thread++)
          {
              int a=0, b=0, c=0;
              int values[4];
              for(int n=thread; n&lt;nIterations; n+=4)
              {
                  values[n] = do_computations(&amp;a, &amp;b, &amp;c);
  #pragma omp barrier
                  if(thread == 0)
                  {
                        for(int i=0; i&lt;4; i++)
                          fprintf(f, "%d\n", values[i]);
                  }
  #pragma omp barrier
              }
          }
  #pragma omp barrier
  </code></pre>
  
  <p>Except, for some inexplicable reason, this is prohibited by the OpenMP specification.</p>
  
  <p>Or I could try</p>
  
  <pre><code>    #pragma omp parallel for
          for(int thread=0; thread&lt;4; thread++)
          {
              int a=0, b=0, c=0;
              for(int n=thread; n&lt;nIterations; n+=4)
              {
                  int value = do_computations(&amp;a, &amp;b, &amp;c);
  #pragma omp ordered
                  {
                      fprintf(f, "%d\n", value);
                  }
              }
          }
      #pragma omp barrier
          fclose(f);
  </code></pre>
  
  <p>But that won't work either, because "An iteration of a loop with a for construct ... must not execute more than one ordered directive."</p>
  
  <p>I don't want to rewrite the code as a single loop and I don't want to exchange loops.</p>
  
  <p>Is there a clean way to do this with OpenMP, without other threading/synchronization tools?</p>