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

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

    For fast debugging c++11 applications and avoid interleaved output I just write small functions like these:

    ...
    #include 
    ...
    mutex m_screen;
    ...
    void msg(char const * const message);
    ...
    void msg(char const * const message)
    {
      m_screen.lock();
      cout << message << endl;
      m_screen.unlock();
    }
    

    I use these types of functions for outputs and if numeric values are needed I just use something like this:

    void msgInt(char const * const message, int const &value);
    ...
    void msgInt(char const * const message, int const &value)
    {
      m_screen.lock();
      cout << message << " = " << value << endl;
      m_screen.unlock();
    }
    

    This is easy and works fine to me, but I don't really know if it is technically correct. So I would be glad to hear your opinions.


    Well, I didn't read this:

    I don't want to search for each occurrence of std::cout and add a line of locking code.

    I'm sorry. However I hope it helps somebody.

提交回复
热议问题