I write a simple program for testing Thread in c++11 but std::cout doesnt work as I expect.
class Printer
{
public:
void exec()
{
I'm sharing the trick from Nicolás given in this question that I find to be more elegant than Howard Hinnant implementation. The idea is to create a temporary ostringstream object and put the protection code on the destructor.
/** Thread safe cout class
* Exemple of use:
* PrintThread{} << "Hello world!" << std::endl;
*/
class PrintThread: public std::ostringstream
{
public:
PrintThread() = default;
~PrintThread()
{
std::lock_guard guard(_mutexPrint);
std::cout << this->str();
}
private:
static std::mutex _mutexPrint;
};
std::mutex PrintThread::_mutexPrint{};
You can then use it as a regular std::cout, from any thread:
PrintThread{} << "val = " << 33 << std::endl;
The object collect data as a regular std::ostringstream. As soon the coma is reached, the object is destroyed and flush all collected information.