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

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

    Since C++20, you can use std::osyncstream wrapper:

    http://en.cppreference.com/w/cpp/io/basic_osyncstream

    {
      std::osyncstream bout(std::cout); // synchronized wrapper for std::cout
      bout << "Hello, ";
      bout << "World!";
      bout << std::endl; // flush is noted, but not yet performed
      bout << "and more!\n";
    } // characters are transferred and std::cout is flushed
    

    It provides the guarantee that all output made to the same final destination buffer (std::cout in the examples above) will be free of data races and will not be interleaved or garbled in any way, as long as every write to the that final destination buffer is made through (possibly different) instances of std::basic_osyncstream.

提交回复
热议问题