I have OpenMP threads that write to the console via cout and cerr. This of course is not safe, since output can be interleaved. I could do something like
#pragma omp critical(cerr)
{
cerr << "my variable: " << variable << endl;
}
It would be nicer if could replace cerr with a thread-safe version, similar to the approach explained in the valgrind DRD manual (http://valgrind.org/docs/manual/drd-manual.html#drd-manual.effective-use) which involves deriving a class from std::ostreambuf. Ideally in the end I would just replace cerr with my own threaded cerr, e.g. simply:
tcerr << "my variable: " << variable << endl;
Such a class could print to the console as soon as it encounters an "endl". I do not mind if lines from different threads are interleaved, but each line should come only from one thread.
I do not really understand how all this streaming in C++ works, it is too complicated. Has anybody such a class or can show me how to create such a class for that purpose?
cout
notcerr
. – Barmarprintf
orwrite
? Build the string in a stringstream, then useprintf
/write
for an atomic write of the whole line... – David Rodríguez - dribeasoperator<<
, which means that the output of different threads can be mixed to produce:myvariable: myvariable: 345
(now go figure whether the values are3
and45
or34
and5
:)) – David Rodríguez - dribeas