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

前端 未结 9 738
庸人自扰
庸人自扰 2020-12-02 10:52

I have a multi-threaded application, which heavily uses std::cout for logging without any locking. In such a case, how can I easily add lock mechanism to make <

9条回答
  •  既然无缘
    2020-12-02 11:14

    I really like the trick from Nicolás given in this question of creating a temporary object and putting 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{} << "my_val=" << val << std::endl;
    

    The object collect data as a regular ostringstream. As soon the coma is reached, the object is destroyed and flush all collected information.

提交回复
热议问题