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

前端 未结 9 758
庸人自扰
庸人自扰 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:04

    I know its an old question, but it helped me a lot with my problem. I created an utility class based on this post answers and I'd like to share my result.

    Considering we use C++11 or latter C++ versions, this class provides print and println functions to compose strings before calling the standard output stream and avoid concurrency problems. These are variadic functions which use templates to print different data types.

    You can check its use in a producer-consumer problem on my github: https://github.com/eloiluiz/threadsBar

    So, here is my code:

    class Console {
    private:
        Console() = default;
    
        inline static void innerPrint(std::ostream &stream) {}
    
        template
        inline static void innerPrint(std::ostream &stream, Head const head, Tail const ...tail) {
            stream << head;
            innerPrint(stream, tail...);
        }
    
    public:
        template
        inline static void print(Head const head, Tail const ...tail) {
            // Create a stream buffer
            std::stringbuf buffer;
            std::ostream stream(&buffer);
            // Feed input parameters to the stream object
            innerPrint(stream, head, tail...);
            // Print into console and flush
            std::cout << buffer.str();
        }
    
        template
        inline static void println(Head const head, Tail const ...tail) {
            print(head, tail..., "\n");
        }
    };
    

提交回复
热议问题