Search code examples
c++multithreadingiostreamstderrsubclassing

A line-based thread-safe std::cerr for C++


What is the easiest way to create my own std::cerr so that it is line-by-line thread-safe.

I am preferably looking for the code to do it.

What I need is so that a line of output (terminated with std::endl) generated by one thread stays as a line of output when I actually see it on my console (and is not mixed with some other thread's output).


Solution: std::cerr is much slower than cstdio. I prefer using fprintf(stderr, "The message") inside of a CriticalSectionLocker class whose constructor acquires a thread-safe lock and the destructor releases it.


Solution

  • This:

    #define myerr(e) {CiriticalSectionLocker crit; std::cerr << e << std::endl;}
    

    works on most compilers for the common case of myerr("ERR: " << message << number).