是标准输出流在C ++线程安全(cout,cerr,clog)? [英] Are standard output streams in C++ thread-safe (cout, cerr, clog)?

查看:215
本文介绍了是标准输出流在C ++线程安全(cout,cerr,clog)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道当前 C ++ 中没有线程的概念,但本文介绍

I know that there is no concept of threads in current C++, but this article is saying:


strong>安全,线程安全,便携式
记录机制

.....

fprintf()函数是threadsafe,
所以即使这个日志是从
中使用不同的线程,输出行
不会加密。

The fprintf() function is threadsafe, so even if this log is used from different threads, the output lines won't be scrambled.

cout cerr clog

这个问题适用于C ++中的所有类型的流类型,如 fstream stringstream

I think this question is applicable to all kind of stream types in C++ also, like fstream and stringstream.

推荐答案

本文针对 fprintf API声明POSIX标准。它没有说到C ++流。这是相当正确的,因为这些流没有这样的保证。

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.

请注意,虽然该文章中的日志类使用C ++流语法, std :: ostringstream 为每个日志记录事件创建和销毁的对象,因此不会在线程之间共享。它使用 fprintf 将内容实际写入控制台。

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.

Microsoft C库使一些声明是POSIX因此本文中的代码可能是相当广泛的可移植性(因为许多其他流行的操作系统符合POSIX)。但这并不意味着标准的C ++流是线程安全的。

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.

这篇关于是标准输出流在C ++线程安全(cout,cerr,clog)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆