我有一个多线程应用程序,它大量使用 std::cout
进行日志记录而没有任何锁定。在这种情况下,如何轻松添加锁机制以使 std::cout
线程安全?
我不想搜索每次出现的 std::cout
并添加一行锁定代码。太乏味了。
有更好的做法吗?
最佳答案
虽然我不能确定这适用于 std 库的每个编译器/版本
但在代码库中我使用 std::cout::operator<<()
它已经是线程安全的了。
我假设你真正想做的事情停止了std::cout
与 operator<<
连接时混合字符串每个字符串多次,跨多个线程。
字符串出现乱码的原因是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/