As already explained, the assumption that printf() is atomic and will not cripple your result, whereas std::cout::operator<<() will not and will spoil things if it is fundamentally wrong.
However, there is still a (tiny) part of the "truth", but on a different level. Let me give you an example:
If I try to use the OpenMP C-style "Hello world", which can give the following:
printf( "Hello from thread %d of %d\n", omp_get_thread_num(), omp_get_num_threads() );
The same C ++ style might look like this:
std::cout << "Hello from thread " << omp_get_thread_num() << " of " << omp_get_num_threads() << std::endl;
And the significant difference between them is that for printf() I call the print method only once with a fully prepared output string, and the C ++ style calls std::cout::operator<<() 5 times, moreover only bits and pieces of lines that may or may not be sent to standard output. Everything can happen inside, and I will not try to take any action. But at least by using printf() here, I increase my chances of a clean output, even if I cannot guarantee it.
Here is a complete example:
#include <iostream> #include <stdio.h> #include <omp.h> int main() { #pragma omp parallel printf( "Hello from thread %d of %d with printf()\n", omp_get_thread_num(), omp_get_num_threads() ); printf( "*** outside of parallel region ***\n" ); #pragma omp parallel std::cout << "Hello from thread " << omp_get_thread_num() << " of " << omp_get_num_threads() << " with std::cout" << std::endl; return 0; }
What on my laptop Linux gives me (GCC 5.2):
~/tmp$ g++ -fopenmp stdout.cc ~/tmp$ ./a.out Hello from thread 3 of 4 with printf() Hello from thread 0 of 4 with printf() Hello from thread 2 of 4 with printf() Hello from thread 1 of 4 with printf() *** outside of parallel region *** Hello from thread Hello from thread Hello from thread Hello from thread 1 of 4 with std::cout23 of 4 with std::cout of 4 with std::cout 0 of 4 with std::cout ~/tmp$
If you look closely, you will see that none of the individual calls to std::cout::operator<<() is broken, but each new call is an opportunity for different threads to race each other and to get the result.
And again, saying that printf() is atomic and will not mess things up, this is wrong, but just for a complex output string it is less likely to be distorted than with std::cout .