I know that there is no concept of threads in current C++
, but this article is saying:
A typesafe, threadsafe, portable logging mechanism
.....
The
fprintf()
function is threadsafe, so even if this log is used from different threads, the output lines won't be scrambled.
What about cout
, cerr
and clog
?
I think this question is applicable to all kind of stream types in C++ also, like fstream
and stringstream
.
Insertion to and extraction from global stream objects ( std::cout, std::cin, std::cerr , and std::clog ) is thread-safe.
A side note: std::cout is thread-safeBut that is only an optical issue. The program is well defined. The remark is valid for all input and output streams.
In C++ input and output are performed in the form of a sequence of bytes or more commonly known as streams. cerr and clog both are associated with the standard C error output stream stderr but the cerr is the unbuffered standard error stream whereas the clog is the buffered standard error stream.
Streams in C++ are not thread-safe by default.
The article makes a claim about the POSIX standard for the fprintf
API. It says nothing about C++ streams. And this is quite correct, as there are no such guarantees on those stream.
Note that although the logging class in that article uses C++ stream syntax, it does this via a std::ostringstream
object that is created and destroyed for every logging event, and so is not shared between threads. It uses fprintf
to actually write the content to the console.
The Microsoft C library makes some claims to be POSIX compliant, and so the code in the article probably is quite widely portable (as many other popular operating systems are POSIX compliant). But this doesn't mean that standard C++ streams are thread-safe.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With