How to easily make std::cout thread-safe?

While I can’t be sure this applies to every compiler / version of std libs
but in the code-base I’m using std::cout::operator<<() it is already thread-safe.

I’m assuming that what you’re really trying to do it stop std::cout from mixing string when concatenating with the operator<< multiple time per string, across multiple threads.

The reason strings get garbled is because there is a “External” race on the operator<<
this can lead to things like this happening.

//Thread 1
std::cout << "the quick brown fox " << "jumped over the lazy dog " << std::endl;

//Thread 2
std::cout << "my mother washes" << " seashells by the sea shore" << std::endl;

//Could just as easily print like this or any other crazy order.
my mother washes the quick brown fox seashells by the sea shore \n
jumped over the lazy dog \n

If that’s the case there is a much simpler answer than making your own thread safe cout or implementing a lock to use with cout.

Simply compose your string before you pass it to cout

For example.

//There are other ways, but stringstream uses << just like cout.. 
std::stringstream msg;
msg << "Error:" << Err_num << ", " << ErrorString( Err_num ) << "\n"; 
std::cout << msg.str();

This way your stings can’t be garbled because they are already fully formed, plus its also a better practice to fully form your strings anyway before dispatching them.

Leave a Comment

tech