[英]std::cout thread safe formatting and io manipulation
想象一下你有两个线程。 第一个线程尝试使用std::dec
将 integer 打印为十进制:
std::cout << std::dec << 123 << std::endl;
第二个线程尝试使用std::hex
将 integer 打印为十六进制:
std::cout << std::hex << 0x321 << std::endl;
是否保证 123 将打印为十进制而 0x321 将打印为十六进制? 如果不是,我该如何在多线程环境中进行正确的std::cout
格式化?
C++20 有std::osyncstream
。 但是在 C++20 之前我们可以使用什么?
从一开始,这不是std::cout
的选项。
如果您只想使用不同的 object,那么简单的方法就是对所需的每个“复合”使用 stringstream,例如:
std::cout << (std::ostringstream{} << std::hex << 0x321 << std::endl).str();
或者,您可以制作自己的 stream class ,在销毁时将所有内容转发到std::cout
(例如,您可以将std::ostringstream
作为成员或继承它):
~MyStringStream(){
std::cout << str();
}
我不建议在实际的std::cout
上更改这一事实,因为其他人不会期望std::cout
以这种或那种不同的方式表现。 然而话虽如此,我认为重定向是可能的,所以我创造了一种方式来展示这一点(有点像黑客:我认为所有做这样的事情都是黑客)以及如何使这成为可能。 请注意,这根本不是一个完整的解决方案,它只是展示了如何通过您自己的 stream class 将std::cout
到 go必要的同步,或者您计划获得额外的级别等。另请注意,我没有考虑这如何干扰std::cout
绑定流(例如std::in
, std::err
),但我想这没什么大不了的。
#include <utility>
#include <string>
#include <iostream>
#include <sstream>
std::stringstream new_out;
class SyncedStreamBuf : public std::stringbuf {
public:
SyncedStreamBuf(){}
virtual int sync() override {
new_out << "From override: " << str();
str("");//empty buffer
return 0;//success
}
};
class SyncedStream : public std::ostream {
public:
SyncedStream() : std::ostream(&syncedStreamBuf_){
}
private:
SyncedStreamBuf syncedStreamBuf_;
};
SyncedStream my_stream;
int main()
{
std::streambuf* cout_buff = std::cout.rdbuf(); // save pointer to std::cout buffer
std::cout.rdbuf(my_stream.rdbuf());//redirect cout to our own 'stuff'
static_cast<std::ostream&>(new_out).rdbuf(cout_buff);//put cout's buffer into a new out stream
new_out << "test: new_out now prints to stdout\n";
std::cout << "some message\n";//<--now goes through our overridden class
std::cout.flush();
std::cout << "you will see this message - didn't flush\n";
}
Output:
test: new_out now prints to stdout
From override: some message
使用 function 打印 output。 output 将仅从此 function 打印。 在此 function 中使用互斥锁。
OutputFunction(int form, const int& value)
{
std::lock_guard<std::mutex> m_OutputMutex;
if(form == 0)// 0 means dec
{
std::cout << std::dec << value << std::endl;
}
elseif(form ==1)
{
std::cout << std::hex << value << std::endl;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.