Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are standard output streams in C++ thread-safe (cout, cerr, clog)?

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.

like image 796
Khaled Alshaya Avatar asked Sep 27 '09 11:09

Khaled Alshaya


People also ask

Is CERR thread-safe?

Insertion to and extraction from global stream objects ( std::cout, std::cin, std::cerr , and std::clog ) is thread-safe.

Is cout 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.

What is CERR and clog?

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.

Are streams thread-safe C++?

Streams in C++ are not thread-safe by default.


1 Answers

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.

like image 74
Daniel Earwicker Avatar answered Oct 27 '22 13:10

Daniel Earwicker