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

旧巷老猫 提交于 2019-11-29 18:18:40

问题


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.


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/1483403/are-standard-output-streams-in-c-thread-safe-cout-cerr-clog

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!