1

I want to parallelize a for-loop in C++ using OpenMP. In that loop I want to print some results:

#pragma omp parallel for
for (int i=0; i<1000000; i++) {
    if (test.successful() == true) {
        std::cout << test.id() << " " << test.result() << std::endl;
    }
}

The result I get without using OpenMP:

3 23923.23
1 32329.32
2 23239.45

However I get the following using a parallel for-loop:

314924.4244.5
434.
4343.43123

How can I avoid such an output?

Gilfoyle
  • 3,282
  • 3
  • 47
  • 83

1 Answers1

0

The reason is the printing is not defined as an atomic operation, thus context switch occurs while printing to the standard output is still ongoing.

Solution: You must make the for loop body an atomic operation, using #pragma omp atomic

#pragma omp parallel for
for (int i=0; i<1000000; i++) {
    if (test.successful() == true) {
        #pragma omp atomic
        std::cout << test.id() << " " << test.result() << std::endl;
    }
}
YSC
  • 38,212
  • 9
  • 96
  • 149
nivpeled
  • 1,810
  • 5
  • 17