Title: output file using openmp for loop
Tags: c++;openmp
Question: I'm using openmp to parallelize a for loop which calculates some values and I want to write the results in one output file (the order doesn't matter). the simplified version of the code I'm using is as following;
#pragma omp parallel for schedule(dynamic)
for(n=0; n<M; n++){
// calculate some parameters, e.g. a,b,c,d
// now write them in the output file which is already opened using the config.dat file
outfile << setprecision(8) << a << ", " << b << ", " << c << ", " << d << "\n";
outfile.close();
most of the time I receive the right outfile but sometimes I have broken lines in the outfile or some lines seem to be mixed up which I guess is due to the fact that more than one core try to write in the output file at the same time.
I would be really grateful if someone can tell me how to solve this issue.
Comment: wrap `outfile <<...` with `#pragma omp critical`

Comment: See [this answer](http://stackoverflow.com/a/33665044/5239503) for a explanation of what's happening and how to fix it.


Here is another answer: As written in one of the comments, you will need a mutex.
However, if you are going to dump large amounts of data, using
#pragma omp critical
could have a large performance impact.
Consider a solution where each thread stores X lines in a private buffer and dumps them all to file in one batch.

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 2, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2016:00:05/30/16', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<c++><openmp>', 'Title': 'output file using openmp for loop', 'ViewCount': 413, 'id': 37527624, 'user_AboutMe': None, 'user_AccountId': 8481327.0, 'user_DisplayName': 'So R Kh', 'user_Reputation': 3.0, 'user_Views': 31.0, 'user_id': 6360947.0}}