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

你。 提交于 2019-11-30 12:42:23

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.

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.

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.

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