views:

878

answers:

3

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.

+5  A: 

That would be an implementation-specific detail. You can ask if Compiler X with Run Time Library Y has thread-safe standard streams, but you can't ask if all implementations do, because implementations are allowed to differ with regard to thread safety. This is part of what it means that C++ has no built-in concept of threads. It's all implementation-specific.

Warren Young
That what I think too :) but the article claims that the code is portable too!
AraK
I would guess that the article's author is simply saying that it works everywhere he's tried it. He probably hasn't tried it on, say, Keil C with HomeGrownRTOS v1.2, or any number of other uncommon combinations.
Warren Young
The article isn't talking about C++ streams.
Daniel Earwicker
@Warren Young - the author of the article isn't that dumb, as it happens. They specifically say what standard must be supported for their code to work.
Daniel Earwicker
@Earwicker, this has nothing todo with being dumb or not, i think. The author claims that it's portable posix code. The pure C function `fprintf` is still not thread safe.
Johannes Schaub - litb
@litb - I think Warren Young attributed a certain naivety to the author of that article, that they were claiming portability based on a few experiments. That's what I took exception to. As you've noticed, the author clearly states that their program is valid on POSIX environments.
Daniel Earwicker
+2  A: 

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.

Daniel Earwicker
+1  A: 

Since the current C++ standard doesn't even acknowledge that there are things called "threads", it certainly doesn't give any guarantees regarding thread-safety at all.

This is all implementation-defined.

sbi