title: How to write to a file in parallel using OpenMp
body: <p>I have the following code which works perfectly in Serial:</p>
  
  <pre><code>while(fread(in, sizeof(in), 1, fp_input) &amp;&amp; ++count){              
        Encode();
        fseek(fp_out, (count-1)*sizeof(out), SEEK_SET);
        fwrite(out, sizeof(out), 1, fp_out);
        time_spent = (double)(stop - start)/CLOCKS_PER_SEC;   
  }
  </code></pre>
  
  <p>To parallelize the code , I use the following OpenMP directives:</p>
  
  <pre><code>#pragma omp parallel private(in, out)
     {   
        while(read(fd_read, in, sizeof(in)) &amp;&amp; ++count){ 
           Encode(); //take input from in and writes to out
           fseek(fp_out, (count-1)*sizeof(out), SEEK_SET);
           fwrite(out, sizeof(out), 1, fp_out);
           time_spent = (double)(stop - start)/CLOCKS_PER_SEC;   
        }   
     }   
  </code></pre>
  
  <p>It is imperative that I maintain order as write into output file so that it may be decrypted later. But I am not able to achieve it, how do structure the OpenMp directives to achieve order in the file write?</p>
  
  <p><strong>Updated the code</strong> to the following and earned significant speedup over the serial code:</p>
  
  <pre><code>while(fread(chunk_input, sizeof(chunk_input), 1, fp_input) == 1){ 
        int block_no = 0;
        #pragma omp parallel for private(block_no)
        for(block_no=0; block_no&lt;CHUNK_SIZE; block_no += 16){
           unsigned char in[16], out[16];
           memcpy(in, &amp;chunk_input[block_no], 16);          
           Encode(in, out);
           memcpy(&amp;chunk_output[block_no], out, 16);
        }          
        fwrite(chunk_output, sizeof(chunk_output), 1, fp_out);
     }
  </code></pre>