Skip to content

Instantly share code, notes, and snippets.

@prwhite
Created March 4, 2022 17:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save prwhite/3c2dddc6159bf1d1b4571ac930988603 to your computer and use it in GitHub Desktop.
Save prwhite/3c2dddc6159bf1d1b4571ac930988603 to your computer and use it in GitHub Desktop.
Cheesy thread-synchronized std::cout output.
////////////////////////////////////////////////////////////////////////////////
// Class to substitute for cout to get synchronization of output.
// Usage: syncout << "foo " << 0xff << syncendl;
using namespace std;
class syncostringstream : public ostringstream {};
#define syncout syncostringstream()
ostream &syncendl(ostream &ostr)
{
if(auto *sostr = dynamic_cast< syncostringstream* >( &ostr ))
{
static mutex m;
unique_lock< mutex > lock(m);
ostr << endl;
cout << sostr->str();
}
else
cerr << "ostream type not an syncostringstream, cannot synchronize output" << endl;
return ostr;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment