using std::cout in multiple threads

前端 未结 4 1911
刺人心
刺人心 2020-12-30 03:58

I write a simple program for testing Thread in c++11 but std::cout doesnt work as I expect.

class Printer
{
public:
    void exec()
    {
               


        
4条回答
  •  南笙
    南笙 (楼主)
    2020-12-30 04:26

    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.

提交回复
热议问题