c++ - 如何轻松使 std::cout 线程安全?

标签 c++ multithreading logging locking iostream

我有一个多线程应用程序,它大量使用 std::cout 进行日志记录而没有任何锁定。在这种情况下,如何轻松添加锁机制以使 std::cout 线程安全?

我不想搜索每次出现的 std::cout 并添加一行锁定代码。太乏味了。

有更好的做法吗?

最佳答案

虽然我不能确定这适用于 std 库的每个编译器/版本 但在代码库中我使用 std::cout::operator<<()它已经是线程安全的了。

我假设你真正想做的事情停止了std::coutoperator<< 连接时混合字符串每个字符串多次,跨多个线程。

字符串出现乱码的原因是operator<< 上存在“外部”竞争。 这可能会导致这样的事情发生。

//Thread 1
std::cout << "the quick brown fox " << "jumped over the lazy dog " << std::endl;

//Thread 2
std::cout << "my mother washes" << " seashells by the sea shore" << std::endl;

//Could just as easily print like this or any other crazy order.
my mother washes the quick brown fox seashells by the sea shore \n
jumped over the lazy dog \n

如果是这种情况,有一个比创建自己的线程安全 cout 或实现与 cout 一起使用的锁要简单得多的答案。

在将字符串传递给 cout 之前只需编写字符串

例如。

//There are other ways, but stringstream uses << just like cout.. 
std::stringstream msg;
msg << "Error:" << Err_num << ", " << ErrorString( Err_num ) << "\n"; 
std::cout << msg.str();

这样你的stings就不会出现乱码,因为它们已经完全形成了,另外,在调度它们之前完全形成你的字符串也是一个更好的做法。

关于c++ - 如何轻松使 std::cout 线程安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14718124/

相关文章:

c++ - 在 Qt 中制作可折叠的 GroupBox - 是什么决定了折叠的大小?

c++ - VS 2015 C++ Redistributable 不在单个 DLL 中?

android - 在单独的线程中从服务中获取 AutoCompleteTextView 建议

Java反射-调用线程内的方法

java - 如何将 log4j 消息路由到唯一的附加程序

c++ - 如何在 C++ 中获取 a 字符串的一部分?

c++ - 从卫星的 ECI 坐标获取地球上的纬度和经度点

Android:如果已经运行,则停止方法被调用两次

Android Logcat 在模拟器中运行良好,在真实设备中运行不佳

node.js - 将 Azure 应用服务的 stdout 和 stderr 日志存储到 Azure Blob 存储中